repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import static org.ethereum.vm.OpCode.Tier.*; /** * Instruction set for the Ethereum Virtual Machine * See Yellow Paper: http://www.gavwood.com/Paper.pdf * - Appendix G. Virtual Machine Specification */ public enum OpCode { // TODO #POC9 Need to make tiers more accurate /** * Halts execution (0x00) */ STOP(0x00, 0, 0, ZeroTier), /* Arithmetic Operations */ /** * (0x01) Addition operation */ ADD(0x01, 2, 1, VeryLowTier), /** * (0x02) Multiplication operation */ MUL(0x02, 2, 1, LowTier), /** * (0x03) Subtraction operations */ SUB(0x03, 2, 1, VeryLowTier), /** * (0x04) Integer division operation */ DIV(0x04, 2, 1, LowTier), /** * (0x05) Signed integer division operation */ SDIV(0x05, 2, 1, LowTier), /** * (0x06) Modulo remainder operation */ MOD(0x06, 2, 1, LowTier), /** * (0x07) Signed modulo remainder operation */ SMOD(0x07, 2, 1, LowTier), /** * (0x08) Addition combined with modulo * remainder operation */ ADDMOD(0x08, 3, 1, MidTier), /** * (0x09) Multiplication combined with modulo * remainder operation */ MULMOD(0x09, 3, 1, MidTier), /** * (0x0a) Exponential operation */ EXP(0x0a, 2, 1, SpecialTier), /** * (0x0b) Extend length of signed integer */ SIGNEXTEND(0x0b, 2, 1, LowTier), /* Bitwise Logic & Comparison Operations */ /** * (0x10) Less-than comparison */ LT(0X10, 2, 1, VeryLowTier), /** * (0x11) Greater-than comparison */ GT(0X11, 2, 1, VeryLowTier), /** * (0x12) Signed less-than comparison */ SLT(0X12, 2, 1, VeryLowTier), /** * (0x13) Signed greater-than comparison */ SGT(0X13, 2, 1, VeryLowTier), /** * (0x14) Equality comparison */ EQ(0X14, 2, 1, VeryLowTier), /** * (0x15) Negation operation */ ISZERO(0x15, 1, 1, VeryLowTier), /** * (0x16) Bitwise AND operation */ AND(0x16, 2, 1, VeryLowTier), /** * (0x17) Bitwise OR operation */ OR(0x17, 2, 1, VeryLowTier), /** * (0x18) Bitwise XOR operation */ XOR(0x18, 2, 1, VeryLowTier), /** * (0x19) Bitwise NOT operationr */ NOT(0x19, 1, 1, VeryLowTier), /** * (0x1a) Retrieve single byte from word */ BYTE(0x1a, 2, 1, VeryLowTier), /** * (0x1b) Shift left */ SHL(0x1b, 2, 1, VeryLowTier), /** * (0x1c) Logical shift right */ SHR(0x1c, 2, 1, VeryLowTier), /** * (0x1d) Arithmetic shift right */ SAR(0x1d, 2, 1, VeryLowTier), /* Cryptographic Operations */ /** * (0x20) Compute SHA3-256 hash */ SHA3(0x20, 2, 1, SpecialTier), /* Environmental Information */ /** * (0x30) Get address of currently * executing account */ ADDRESS(0x30, 0, 1, BaseTier), /** * (0x31) Get balance of the given account */ BALANCE(0x31, 1, 1, ExtTier), /** * (0x32) Get execution origination address */ ORIGIN(0x32, 0, 1, BaseTier), /** * (0x33) Get caller address */ CALLER(0x33, 0, 1, BaseTier), /** * (0x34) Get deposited value by the * instruction/transaction responsible * for this execution */ CALLVALUE(0x34, 0, 1, BaseTier), /** * (0x35) Get input data of current * environment */ CALLDATALOAD(0x35, 1, 1, VeryLowTier), /** * (0x36) Get size of input data in current * environment */ CALLDATASIZE(0x36, 0, 1, BaseTier), /** * (0x37) Copy input data in current * environment to memory */ CALLDATACOPY(0x37, 3, 0, VeryLowTier), /** * (0x38) Get size of code running in * current environment */ CODESIZE(0x38, 0, 1, BaseTier), /** * (0x39) Copy code running in current * environment to memory */ CODECOPY(0x39, 3, 0, VeryLowTier), // [len code_start mem_start CODECOPY] RETURNDATASIZE(0x3d, 0, 1, BaseTier), RETURNDATACOPY(0x3e, 3, 0, VeryLowTier), /** * (0x3a) Get price of gas in current * environment */ GASPRICE(0x3a, 0, 1, BaseTier), /** * (0x3b) Get size of code running in * current environment with given offset */ EXTCODESIZE(0x3b, 1, 1, ExtTier), /** * (0x3c) Copy code running in current * environment to memory with given offset */ EXTCODECOPY(0x3c, 4, 0, ExtTier), /** * (0x3f) Returns the keccak256 hash of * a contract’s code */ EXTCODEHASH(0x3f, 1,1 , ExtTier), /* Block Information */ /** * (0x40) Get hash of most recent * complete block */ BLOCKHASH(0x40, 1, 1, ExtTier), /** * (0x41) Get the block’s coinbase address */ COINBASE(0x41, 0, 1, BaseTier), /** * (x042) Get the block’s timestamp */ TIMESTAMP(0x42, 0, 1, BaseTier), /** * (0x43) Get the block’s number */ NUMBER(0x43, 0, 1, BaseTier), /** * (0x44) Get the block’s difficulty */ DIFFICULTY(0x44, 0, 1, BaseTier), /** * (0x45) Get the block’s gas limit */ GASLIMIT(0x45, 0, 1, BaseTier), /* Memory, Storage and Flow Operations */ /** * (0x50) Remove item from stack */ POP(0x50, 1, 0, BaseTier), /** * (0x51) Load word from memory */ MLOAD(0x51, 1, 1, VeryLowTier), /** * (0x52) Save word to memory */ MSTORE(0x52, 2, 0, VeryLowTier), /** * (0x53) Save byte to memory */ MSTORE8(0x53, 2, 0, VeryLowTier), /** * (0x54) Load word from storage */ SLOAD(0x54, 1, 1, SpecialTier), /** * (0x55) Save word to storage */ SSTORE(0x55, 2, 0, SpecialTier), /** * (0x56) Alter the program counter */ JUMP(0x56, 1, 0, MidTier), /** * (0x57) Conditionally alter the program * counter */ JUMPI(0x57, 2, 0, HighTier), /** * (0x58) Get the program counter */ PC(0x58, 0, 1, BaseTier), /** * (0x59) Get the size of active memory */ MSIZE(0x59, 0, 1, BaseTier), /** * (0x5a) Get the amount of available gas */ GAS(0x5a, 0, 1, BaseTier), /** * (0x5b) */ JUMPDEST(0x5b, 0, 0, SpecialTier), /* Push Operations */ /** * (0x60) Place 1-byte item on stack */ PUSH1(0x60, 0, 1, VeryLowTier), /** * (0x61) Place 2-byte item on stack */ PUSH2(0x61, 0, 1, VeryLowTier), /** * (0x62) Place 3-byte item on stack */ PUSH3(0x62, 0, 1, VeryLowTier), /** * (0x63) Place 4-byte item on stack */ PUSH4(0x63, 0, 1, VeryLowTier), /** * (0x64) Place 5-byte item on stack */ PUSH5(0x64, 0, 1, VeryLowTier), /** * (0x65) Place 6-byte item on stack */ PUSH6(0x65, 0, 1, VeryLowTier), /** * (0x66) Place 7-byte item on stack */ PUSH7(0x66, 0, 1, VeryLowTier), /** * (0x67) Place 8-byte item on stack */ PUSH8(0x67, 0, 1, VeryLowTier), /** * (0x68) Place 9-byte item on stack */ PUSH9(0x68, 0, 1, VeryLowTier), /** * (0x69) Place 10-byte item on stack */ PUSH10(0x69, 0, 1, VeryLowTier), /** * (0x6a) Place 11-byte item on stack */ PUSH11(0x6a, 0, 1, VeryLowTier), /** * (0x6b) Place 12-byte item on stack */ PUSH12(0x6b, 0, 1, VeryLowTier), /** * (0x6c) Place 13-byte item on stack */ PUSH13(0x6c, 0, 1, VeryLowTier), /** * (0x6d) Place 14-byte item on stack */ PUSH14(0x6d, 0, 1, VeryLowTier), /** * (0x6e) Place 15-byte item on stack */ PUSH15(0x6e, 0, 1, VeryLowTier), /** * (0x6f) Place 16-byte item on stack */ PUSH16(0x6f, 0, 1, VeryLowTier), /** * (0x70) Place 17-byte item on stack */ PUSH17(0x70, 0, 1, VeryLowTier), /** * (0x71) Place 18-byte item on stack */ PUSH18(0x71, 0, 1, VeryLowTier), /** * (0x72) Place 19-byte item on stack */ PUSH19(0x72, 0, 1, VeryLowTier), /** * (0x73) Place 20-byte item on stack */ PUSH20(0x73, 0, 1, VeryLowTier), /** * (0x74) Place 21-byte item on stack */ PUSH21(0x74, 0, 1, VeryLowTier), /** * (0x75) Place 22-byte item on stack */ PUSH22(0x75, 0, 1, VeryLowTier), /** * (0x76) Place 23-byte item on stack */ PUSH23(0x76, 0, 1, VeryLowTier), /** * (0x77) Place 24-byte item on stack */ PUSH24(0x77, 0, 1, VeryLowTier), /** * (0x78) Place 25-byte item on stack */ PUSH25(0x78, 0, 1, VeryLowTier), /** * (0x79) Place 26-byte item on stack */ PUSH26(0x79, 0, 1, VeryLowTier), /** * (0x7a) Place 27-byte item on stack */ PUSH27(0x7a, 0, 1, VeryLowTier), /** * (0x7b) Place 28-byte item on stack */ PUSH28(0x7b, 0, 1, VeryLowTier), /** * (0x7c) Place 29-byte item on stack */ PUSH29(0x7c, 0, 1, VeryLowTier), /** * (0x7d) Place 30-byte item on stack */ PUSH30(0x7d, 0, 1, VeryLowTier), /** * (0x7e) Place 31-byte item on stack */ PUSH31(0x7e, 0, 1, VeryLowTier), /** * (0x7f) Place 32-byte (full word) * item on stack */ PUSH32(0x7f, 0, 1, VeryLowTier), /* Duplicate Nth item from the stack */ /** * (0x80) Duplicate 1st item on stack */ DUP1(0x80, 1, 2, VeryLowTier), /** * (0x81) Duplicate 2nd item on stack */ DUP2(0x81, 2, 3, VeryLowTier), /** * (0x82) Duplicate 3rd item on stack */ DUP3(0x82, 3, 4, VeryLowTier), /** * (0x83) Duplicate 4th item on stack */ DUP4(0x83, 4, 5, VeryLowTier), /** * (0x84) Duplicate 5th item on stack */ DUP5(0x84, 5, 6, VeryLowTier), /** * (0x85) Duplicate 6th item on stack */ DUP6(0x85, 6, 7, VeryLowTier), /** * (0x86) Duplicate 7th item on stack */ DUP7(0x86, 7, 8, VeryLowTier), /** * (0x87) Duplicate 8th item on stack */ DUP8(0x87, 8, 9, VeryLowTier), /** * (0x88) Duplicate 9th item on stack */ DUP9(0x88, 9, 10, VeryLowTier), /** * (0x89) Duplicate 10th item on stack */ DUP10(0x89, 10, 11, VeryLowTier), /** * (0x8a) Duplicate 11th item on stack */ DUP11(0x8a, 11, 12, VeryLowTier), /** * (0x8b) Duplicate 12th item on stack */ DUP12(0x8b, 12, 13, VeryLowTier), /** * (0x8c) Duplicate 13th item on stack */ DUP13(0x8c, 13, 14, VeryLowTier), /** * (0x8d) Duplicate 14th item on stack */ DUP14(0x8d, 14, 15, VeryLowTier), /** * (0x8e) Duplicate 15th item on stack */ DUP15(0x8e, 15, 16, VeryLowTier), /** * (0x8f) Duplicate 16th item on stack */ DUP16(0x8f, 16, 17, VeryLowTier), /* Swap the Nth item from the stack with the top */ /** * (0x90) Exchange 2nd item from stack with the top */ SWAP1(0x90, 2, 2, VeryLowTier), /** * (0x91) Exchange 3rd item from stack with the top */ SWAP2(0x91, 3, 3, VeryLowTier), /** * (0x92) Exchange 4th item from stack with the top */ SWAP3(0x92, 4, 4, VeryLowTier), /** * (0x93) Exchange 5th item from stack with the top */ SWAP4(0x93, 5, 5, VeryLowTier), /** * (0x94) Exchange 6th item from stack with the top */ SWAP5(0x94, 6, 6, VeryLowTier), /** * (0x95) Exchange 7th item from stack with the top */ SWAP6(0x95, 7, 7, VeryLowTier), /** * (0x96) Exchange 8th item from stack with the top */ SWAP7(0x96, 8, 8, VeryLowTier), /** * (0x97) Exchange 9th item from stack with the top */ SWAP8(0x97, 9, 9, VeryLowTier), /** * (0x98) Exchange 10th item from stack with the top */ SWAP9(0x98, 10, 10, VeryLowTier), /** * (0x99) Exchange 11th item from stack with the top */ SWAP10(0x99, 11, 11,VeryLowTier), /** * (0x9a) Exchange 12th item from stack with the top */ SWAP11(0x9a, 12, 12, VeryLowTier), /** * (0x9b) Exchange 13th item from stack with the top */ SWAP12(0x9b, 13, 13, VeryLowTier), /** * (0x9c) Exchange 14th item from stack with the top */ SWAP13(0x9c, 14, 14, VeryLowTier), /** * (0x9d) Exchange 15th item from stack with the top */ SWAP14(0x9d, 15, 15, VeryLowTier), /** * (0x9e) Exchange 16th item from stack with the top */ SWAP15(0x9e, 16, 16, VeryLowTier), /** * (0x9f) Exchange 17th item from stack with the top */ SWAP16(0x9f, 17, 17, VeryLowTier), /** * (0xa[n]) log some data for some addres with 0..n tags [addr [tag0..tagn] data] */ LOG0(0xa0, 2, 0, SpecialTier), LOG1(0xa1, 3, 0, SpecialTier), LOG2(0xa2, 4, 0, SpecialTier), LOG3(0xa3, 5, 0, SpecialTier), LOG4(0xa4, 6, 0, SpecialTier), /* System operations */ /** * (0xf0) Create a new account with associated code */ CREATE(0xf0, 3, 1, SpecialTier), // [in_size] [in_offs] [gas_val] CREATE /** * (cxf1) Message-call into an account */ CALL(0xf1, 7, 1, SpecialTier, CallFlags.Call, CallFlags.HasValue), // [out_data_size] [out_data_start] [in_data_size] [in_data_start] [value] [to_addr] // [gas] CALL /** * (0xf2) Calls self, but grabbing the code from the * TO argument instead of from one's own address */ CALLCODE(0xf2, 7, 1, SpecialTier, CallFlags.Call, CallFlags.HasValue, CallFlags.Stateless), /** * (0xf3) Halt execution returning output data */ RETURN(0xf3, 2, 0, ZeroTier), /** * (0xf4) similar in idea to CALLCODE, except that it propagates the sender and value * from the parent scope to the child scope, ie. the call created has the same sender * and value as the original call. * also the Value parameter is omitted for this opCode */ DELEGATECALL(0xf4, 6, 1, SpecialTier, CallFlags.Call, CallFlags.Stateless, CallFlags.Delegate), /** * (0xf5) Skinny CREATE2, same as CREATE but with deterministic address */ CREATE2(0xf5, 4, 1, SpecialTier), /** * opcode that can be used to call another contract (or itself) while disallowing any * modifications to the state during the call (and its subcalls, if present). * Any opcode that attempts to perform such a modification (see below for details) * will result in an exception instead of performing the modification. */ STATICCALL(0xfa, 6, 1, SpecialTier, CallFlags.Call, CallFlags.Static), /** * (0xfd) The `REVERT` instruction will stop execution, roll back all state changes done so far * and provide a pointer to a memory section, which can be interpreted as an error code or message. * While doing so, it will not consume all the remaining gas. */ REVERT(0xfd, 2, 0, ZeroTier), /** * (0xff) Halt execution and register account for * later deletion */ SUICIDE(0xff, 1, 0, ZeroTier); private final byte opcode; private final int require; private final Tier tier; private final int ret; private final EnumSet<CallFlags> callFlags; private static final OpCode[] intToTypeMap = new OpCode[256]; private static final Map<String, Byte> stringToByteMap = new HashMap<>(); static { for (OpCode type : OpCode.values()) { intToTypeMap[type.opcode & 0xFF] = type; stringToByteMap.put(type.name(), type.opcode); } } //require = required args //return = required return private OpCode(int op, int require, int ret, Tier tier, CallFlags ... callFlags) { this.opcode = (byte) op; this.require = require; this.tier = tier; this.ret = ret; this.callFlags = callFlags.length == 0 ? EnumSet.noneOf(CallFlags.class) : EnumSet.copyOf(Arrays.asList(callFlags)); } public byte val() { return opcode; } /** * Returns the mininum amount of items required on the stack for this operation * * @return minimum amount of expected items on the stack */ public int require() { return require; } public int ret() { return ret; } public int asInt() { return opcode; } public static boolean contains(String code) { return stringToByteMap.containsKey(code.trim()); } public static byte byteVal(String code) { return stringToByteMap.get(code); } public static OpCode code(byte code) { return intToTypeMap[code & 0xFF]; } private EnumSet<CallFlags> getCallFlags() { return callFlags; } /** * Indicates that opcode is a call */ public boolean isCall() { return getCallFlags().contains(CallFlags.Call); } private void checkCall() { if (!isCall()) throw new RuntimeException("Opcode is not a call: " + this); } /** * Indicates that the code is executed in the context of the caller */ public boolean callIsStateless() { checkCall(); return getCallFlags().contains(CallFlags.Stateless); } /** * Indicates that the opcode has value parameter (3rd on stack) */ public boolean callHasValue() { checkCall(); return getCallFlags().contains(CallFlags.HasValue); } /** * Indicates that any state modifications are disallowed during the call */ public boolean callIsStatic() { checkCall(); return getCallFlags().contains(CallFlags.Static); } /** * Indicates that value and message sender are propagated from parent to child scope */ public boolean callIsDelegate() { checkCall(); return getCallFlags().contains(CallFlags.Delegate); } public Tier getTier() { return this.tier; } public enum Tier { ZeroTier(0), BaseTier(2), VeryLowTier(3), LowTier(5), MidTier(8), HighTier(10), ExtTier(20), SpecialTier(1), //TODO #POC9 is this correct?? "multiparam" from cpp InvalidTier(0); private final int level; private Tier(int level) { this.level = level; } public int asInt() { return level; } } private enum CallFlags { /** * Indicates that opcode is a call */ Call, /** * Indicates that the code is executed in the context of the caller */ Stateless, /** * Indicates that the opcode has value parameter (3rd on stack) */ HasValue, /** * Indicates that any state modifications are disallowed during the call */ Static, /** * Indicates that value and message sender are propagated from parent to child scope */ Delegate } }
20,195
24.119403
103
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.util.Arrays; import static org.ethereum.util.ByteUtil.intToBytes; import static org.ethereum.util.ByteUtil.longToBytes; import static org.ethereum.util.ByteUtil.numberOfLeadingZeros; import static org.ethereum.util.ByteUtil.toHexString; /** * DataWord is the 32-byte array representation of a 256-bit number * Calculations can be done on this word with other DataWords * DataWord is immutable. Use one of `of` factories for instance creation. * * @author Roman Mandeleil * @since 01.06.2014 */ public final class DataWord implements Comparable<DataWord> { /* Maximum value of the DataWord */ public static final int MAX_POW = 256; public static final BigInteger _2_256 = BigInteger.valueOf(2).pow(MAX_POW); public static final BigInteger MAX_VALUE = _2_256.subtract(BigInteger.ONE); public static final DataWord ZERO = new DataWord(new byte[32]); public static final DataWord ONE = DataWord.of((byte) 1); public static final long MEM_SIZE = 32 + 16 + 16; private final byte[] data; /** * Unsafe private constructor * Doesn't guarantee immutability if byte[] contents are changed later * Use one of factory methods instead: * - {@link #of(byte[])} * - {@link #of(ByteArrayWrapper)} * - {@link #of(String)} * - {@link #of(long)} * - {@link #of(int)} * @param data Byte Array[32] which is guaranteed to be immutable */ private DataWord(byte[] data) { if (data == null || data.length != 32) throw new RuntimeException("Input byte array should have 32 bytes in it!"); this.data = data; } public static DataWord of(byte[] data) { if (data == null || data.length == 0) { return DataWord.ZERO; } int leadingZeroBits = numberOfLeadingZeros(data); int valueBits = 8 * data.length - leadingZeroBits; if (valueBits <= 8) { if (data[data.length - 1] == 0) return DataWord.ZERO; if (data[data.length - 1] == 1) return DataWord.ONE; } if (data.length == 32) return new DataWord(Arrays.copyOf(data, data.length)); else if (data.length <= 32) { byte[] bytes = new byte[32]; System.arraycopy(data, 0, bytes, 32 - data.length, data.length); return new DataWord(bytes); } else { throw new RuntimeException(String.format("Data word can't exceed 32 bytes: 0x%s", ByteUtil.toHexString(data))); } } public static DataWord of(ByteArrayWrapper wrappedData) { return of(wrappedData.getData()); } @JsonCreator public static DataWord of(String data) { return of(Hex.decode(data)); } public static DataWord of(byte num) { byte[] bb = new byte[32]; bb[31] = num; return new DataWord(bb); } public static DataWord of(int num) { return of(intToBytes(num)); } public static DataWord of(long num) { return of(longToBytes(num)); } /** * Returns instance data * Actually copy of internal byte array is provided * in order to protect DataWord immutability * @return instance data */ public byte[] getData() { return Arrays.copyOf(data, data.length); } /** * Returns copy of instance data * @return copy of instance data */ private byte[] copyData() { return Arrays.copyOf(data, data.length); } public byte[] getNoLeadZeroesData() { return ByteUtil.stripLeadingZeroes(copyData()); } public byte[] getLast20Bytes() { return Arrays.copyOfRange(data, 12, data.length); } public BigInteger value() { return new BigInteger(1, data); } /** * Converts this DataWord to an int, checking for lost information. * If this DataWord is out of the possible range for an int result * then an ArithmeticException is thrown. * * @return this DataWord converted to an int. * @throws ArithmeticException - if this will not fit in an int. */ public int intValue() { int intVal = 0; for (byte aData : data) { intVal = (intVal << 8) + (aData & 0xff); } return intVal; } /** * In case of int overflow returns Integer.MAX_VALUE * otherwise works as #intValue() */ public int intValueSafe() { int bytesOccupied = bytesOccupied(); int intValue = intValue(); if (bytesOccupied > 4 || intValue < 0) return Integer.MAX_VALUE; return intValue; } /** * Converts this DataWord to a long, checking for lost information. * If this DataWord is out of the possible range for a long result * then an ArithmeticException is thrown. * * @return this DataWord converted to a long. * @throws ArithmeticException - if this will not fit in a long. */ public long longValue() { long longVal = 0; for (byte aData : data) { longVal = (longVal << 8) + (aData & 0xff); } return longVal; } /** * In case of long overflow returns Long.MAX_VALUE * otherwise works as #longValue() */ public long longValueSafe() { int bytesOccupied = bytesOccupied(); long longValue = longValue(); if (bytesOccupied > 8 || longValue < 0) return Long.MAX_VALUE; return longValue; } public BigInteger sValue() { return new BigInteger(data); } public String bigIntValue() { return new BigInteger(data).toString(); } public boolean isZero() { if (this == ZERO) return true; return this.compareTo(ZERO) == 0; } // only in case of signed operation // when the number is explicit defined // as negative public boolean isNegative() { int result = data[0] & 0x80; return result == 0x80; } public DataWord and(DataWord word) { byte[] newData = this.copyData(); for (int i = 0; i < this.data.length; ++i) { newData[i] &= word.data[i]; } return new DataWord(newData); } public DataWord or(DataWord word) { byte[] newData = this.copyData(); for (int i = 0; i < this.data.length; ++i) { newData[i] |= word.data[i]; } return new DataWord(newData); } public DataWord xor(DataWord word) { byte[] newData = this.copyData(); for (int i = 0; i < this.data.length; ++i) { newData[i] ^= word.data[i]; } return new DataWord(newData); } public DataWord negate() { if (this.isZero()) return ZERO; return bnot().add(DataWord.ONE); } public DataWord bnot() { if (this.isZero()) { return new DataWord(ByteUtil.copyToArray(MAX_VALUE)); } return new DataWord(ByteUtil.copyToArray(MAX_VALUE.subtract(this.value()))); } // By : Holger // From : http://stackoverflow.com/a/24023466/459349 public DataWord add(DataWord word) { byte[] newData = new byte[32]; for (int i = 31, overflow = 0; i >= 0; i--) { int v = (this.data[i] & 0xff) + (word.data[i] & 0xff) + overflow; newData[i] = (byte) v; overflow = v >>> 8; } return new DataWord(newData); } // old add-method with BigInteger quick hack public DataWord add2(DataWord word) { BigInteger result = value().add(word.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } // TODO: mul can be done in more efficient way // TODO: with shift left shift right trick // TODO without BigInteger quick hack public DataWord mul(DataWord word) { BigInteger result = value().multiply(word.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } // TODO: improve with no BigInteger public DataWord div(DataWord word) { if (word.isZero()) { return ZERO; } BigInteger result = value().divide(word.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } // TODO: improve with no BigInteger public DataWord sDiv(DataWord word) { if (word.isZero()) { return ZERO; } BigInteger result = sValue().divide(word.sValue()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } // TODO: improve with no BigInteger public DataWord sub(DataWord word) { BigInteger result = value().subtract(word.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } // TODO: improve with no BigInteger public DataWord exp(DataWord word) { BigInteger newData = value().modPow(word.value(), _2_256); return new DataWord(ByteUtil.copyToArray(newData)); } // TODO: improve with no BigInteger public DataWord mod(DataWord word) { if (word.isZero()) { return ZERO; } BigInteger result = value().mod(word.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } public DataWord sMod(DataWord word) { if (word.isZero()) { return ZERO; } BigInteger result = sValue().abs().mod(word.sValue().abs()); result = (sValue().signum() == -1) ? result.negate() : result; return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } public DataWord addmod(DataWord word1, DataWord word2) { if (word2.isZero()) { return ZERO; } BigInteger result = value().add(word1.value()).mod(word2.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } public DataWord mulmod(DataWord word1, DataWord word2) { if (this.isZero() || word1.isZero() || word2.isZero()) { return ZERO; } BigInteger result = value().multiply(word1.value()).mod(word2.value()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } /** * Shift left, both this and input arg are treated as unsigned * @param arg * @return this << arg */ public DataWord shiftLeft(DataWord arg) { if (arg.value().compareTo(BigInteger.valueOf(MAX_POW)) >= 0) { return DataWord.ZERO; } BigInteger result = value().shiftLeft(arg.intValueSafe()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } /** * Shift right, both this and input arg are treated as unsigned * @param arg * @return this >> arg */ public DataWord shiftRight(DataWord arg) { if (arg.value().compareTo(BigInteger.valueOf(MAX_POW)) >= 0) { return DataWord.ZERO; } BigInteger result = value().shiftRight(arg.intValueSafe()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } /** * Shift right, this is signed, while input arg is treated as unsigned * @param arg * @return this >> arg */ public DataWord shiftRightSigned(DataWord arg) { if (arg.value().compareTo(BigInteger.valueOf(MAX_POW)) >= 0) { if (this.isNegative()) { return DataWord.ONE.negate(); } else { return DataWord.ZERO; } } BigInteger result = sValue().shiftRight(arg.intValueSafe()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); } @JsonValue @Override public String toString() { return toHexString(data); } public String toPrefixString() { byte[] pref = getNoLeadZeroesData(); if (pref.length == 0) return ""; if (pref.length < 7) return Hex.toHexString(pref); return Hex.toHexString(pref).substring(0, 6); } public String shortHex() { String hexValue = Hex.toHexString(getNoLeadZeroesData()).toUpperCase(); return "0x" + hexValue.replaceFirst("^0+(?!$)", ""); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataWord that = (DataWord) o; return java.util.Arrays.equals(this.data, that.data); } @Override public int hashCode() { return java.util.Arrays.hashCode(data); } @Override public int compareTo(DataWord o) { if (o == null) return -1; int result = FastByteComparisons.compareTo( data, 0, data.length, o.data, 0, o.data.length); // Convert result into -1, 0 or 1 as is the convention return (int) Math.signum(result); } public DataWord signExtend(byte k) { if (0 > k || k > 31) throw new IndexOutOfBoundsException(); byte mask = this.sValue().testBit((k * 8) + 7) ? (byte) 0xff : 0; byte[] newData = this.copyData(); for (int i = 31; i > k; i--) { newData[31 - i] = mask; } return new DataWord(newData); } public int bytesOccupied() { int firstNonZero = ByteUtil.firstNonZeroByte(data); if (firstNonZero == -1) return 0; return 31 - firstNonZero + 1; } public boolean isHex(String hex) { return Hex.toHexString(data).equals(hex); } public String asString() { return new String(getNoLeadZeroesData()); } }
14,724
29.423554
123
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/LogInfo.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm; import org.ethereum.core.Bloom; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.MemSizeEstimator; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPItem; import org.ethereum.util.RLPList; import java.util.ArrayList; import java.util.List; import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator; import static org.ethereum.util.ByteUtil.toHexString; /** * @author Roman Mandeleil * @since 19.11.2014 */ public class LogInfo { byte[] address = new byte[]{}; List<DataWord> topics = new ArrayList<>(); byte[] data = new byte[]{}; public LogInfo(byte[] rlp) { RLPList params = RLP.decode2(rlp); RLPList logInfo = (RLPList) params.get(0); RLPItem address = (RLPItem) logInfo.get(0); RLPList topics = (RLPList) logInfo.get(1); RLPItem data = (RLPItem) logInfo.get(2); this.address = address.getRLPData() != null ? address.getRLPData() : new byte[]{}; this.data = data.getRLPData() != null ? data.getRLPData() : new byte[]{}; for (RLPElement topic1 : topics) { byte[] topic = topic1.getRLPData(); this.topics.add(DataWord.of(topic)); } } public LogInfo(byte[] address, List<DataWord> topics, byte[] data) { this.address = (address != null) ? address : new byte[]{}; this.topics = (topics != null) ? topics : new ArrayList<DataWord>(); this.data = (data != null) ? data : new byte[]{}; } public byte[] getAddress() { return address; } public List<DataWord> getTopics() { return topics; } public byte[] getData() { return data; } /* [address, [topic, topic ...] data] */ public byte[] getEncoded() { byte[] addressEncoded = RLP.encodeElement(this.address); byte[][] topicsEncoded = null; if (topics != null) { topicsEncoded = new byte[topics.size()][]; int i = 0; for (DataWord topic : topics) { byte[] topicData = topic.getData(); topicsEncoded[i] = RLP.encodeElement(topicData); ++i; } } byte[] dataEncoded = RLP.encodeElement(data); return RLP.encodeList(addressEncoded, RLP.encodeList(topicsEncoded), dataEncoded); } public Bloom getBloom() { Bloom ret = Bloom.create(HashUtil.sha3(address)); for (DataWord topic : topics) { byte[] topicData = topic.getData(); ret.or(Bloom.create(HashUtil.sha3(topicData))); } return ret; } @Override public String toString() { StringBuilder topicsStr = new StringBuilder(); topicsStr.append("["); for (DataWord topic : topics) { String topicStr = toHexString(topic.getData()); topicsStr.append(topicStr).append(" "); } topicsStr.append("]"); return "LogInfo{" + "address=" + toHexString(address) + ", topics=" + topicsStr + ", data=" + toHexString(data) + '}'; } public static final MemSizeEstimator<LogInfo> MemEstimator = log -> ByteArrayEstimator.estimateSize(log.address) + ByteArrayEstimator.estimateSize(log.data) + log.topics.size() * DataWord.MEM_SIZE + 16; }
4,230
30.574627
90
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/hook/VMHook.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.hook; import org.ethereum.vm.OpCode; import org.ethereum.vm.program.Program; /** * Created by Anton Nashatyrev on 15.02.2016. */ public interface VMHook { default void startPlay(Program program) { } default void step(Program program, OpCode opcode) { } default void stopPlay(Program program) { } default boolean isEmpty() { return false; } VMHook EMPTY = new VMHook() { @Override public boolean isEmpty() { return true; } }; }
1,334
26.8125
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/hook/RootVmHook.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.hook; import org.ethereum.vm.OpCode; import org.ethereum.vm.program.Program; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.Optional; import java.util.function.Consumer; /** * Primary {@link VMHook} implementation, that accepts other VM hook components to safely proxy all invocations to them. */ @Primary @Component public class RootVmHook implements VMHook { private static final Logger logger = LoggerFactory.getLogger("VM"); private VMHook[] hooks; @Autowired public RootVmHook(Optional<VMHook[]> hooks) { this.hooks = hooks.orElseGet(() -> new VMHook[] {}); } private void proxySafeToAll(Consumer<VMHook> action) { for (VMHook hook : hooks) { if (hook.isEmpty()) continue; try { action.accept(hook); } catch (Throwable t) { logger.error("VM hook execution error: ", t); } } } @Override public void startPlay(Program program) { proxySafeToAll(hook -> hook.startPlay(program)); } @Override public void step(Program program, OpCode opcode) { proxySafeToAll(hook -> hook.step(program, opcode)); } @Override public void stopPlay(Program program) { proxySafeToAll(hook -> hook.stopPlay(program)); } @Override public boolean isEmpty() { return hooks.length == 0 || emptyHooksCount() == hooks.length; } private long emptyHooksCount() { return Arrays.stream(hooks).filter(VMHook::isEmpty).count(); } }
2,574
29.654762
120
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/trace/ProgramTrace.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import org.ethereum.config.SystemProperties; import org.ethereum.vm.DataWord; import org.ethereum.vm.OpCode; import org.ethereum.vm.program.invoke.ProgramInvoke; import org.spongycastle.util.encoders.Hex; import java.util.ArrayList; import java.util.List; import static java.lang.String.format; import static org.ethereum.util.ByteUtil.toHexString; import static org.ethereum.vm.trace.Serializers.serializeFieldsOnly; public class ProgramTrace { private List<Op> ops = new ArrayList<>(); private String result; private String error; private String contractAddress; public ProgramTrace() { this(null, null); } public ProgramTrace(SystemProperties config, ProgramInvoke programInvoke) { if (programInvoke != null && config.vmTrace()) { contractAddress = Hex.toHexString(programInvoke.getOwnerAddress().getLast20Bytes()); } } public List<Op> getOps() { return ops; } public void setOps(List<Op> ops) { this.ops = ops; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getContractAddress() { return contractAddress; } public void setContractAddress(String contractAddress) { this.contractAddress = contractAddress; } public ProgramTrace result(byte[] result) { setResult(toHexString(result)); return this; } public ProgramTrace error(Exception error) { setError(error == null ? "" : format("%s: %s", error.getClass(), error.getMessage())); return this; } public Op addOp(byte code, int pc, int deep, DataWord gas, OpActions actions) { Op op = new Op(); op.setActions(actions); op.setCode(OpCode.code(code)); op.setDeep(deep); op.setGas(gas.value()); op.setPc(pc); ops.add(op); return op; } /** * Used for merging sub calls execution. */ public void merge(ProgramTrace programTrace) { this.ops.addAll(programTrace.ops); } public String asJsonString(boolean formatted) { return serializeFieldsOnly(this, formatted); } @Override public String toString() { return asJsonString(true); } }
3,282
26.132231
96
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/trace/Serializers.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import org.ethereum.vm.DataWord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.io.IOException; public final class Serializers { private static final Logger LOGGER = LoggerFactory.getLogger("vmtrace"); public static class DataWordSerializer extends JsonSerializer<DataWord> { @Override public void serialize(DataWord gas, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(gas.value().toString()); } } public static class ByteArraySerializer extends JsonSerializer<byte[]> { @Override public void serialize(byte[] memory, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(Hex.toHexString(memory)); } } public static class OpCodeSerializer extends JsonSerializer<Byte> { @Override public void serialize(Byte op, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(org.ethereum.vm.OpCode.code(op).name()); } } public static String serializeFieldsOnly(Object value, boolean pretty) { try { ObjectMapper mapper = createMapper(pretty); mapper.setVisibilityChecker(fieldsOnlyVisibilityChecker(mapper)); return mapper.writeValueAsString(value); } catch (Exception e) { LOGGER.error("JSON serialization error: ", e); return "{}"; } } private static VisibilityChecker<?> fieldsOnlyVisibilityChecker(ObjectMapper mapper) { return mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE); } public static ObjectMapper createMapper(boolean pretty) { ObjectMapper mapper = new ObjectMapper(); if (pretty) { mapper.enable(SerializationFeature.INDENT_OUTPUT); } return mapper; } }
3,517
37.659341
139
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/trace/OpActions.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import com.fasterxml.jackson.annotation.JsonInclude; import org.ethereum.vm.DataWord; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.ethereum.util.ByteUtil.toHexString; public class OpActions { @JsonInclude(JsonInclude.Include.NON_NULL) public static class Action { public enum Name { pop, push, swap, extend, write, put, remove, clear; } private Name name; private Map<String, Object> params; public Name getName() { return name; } public void setName(Name name) { this.name = name; } public Map<String, Object> getParams() { return params; } public void setParams(Map<String, Object> params) { this.params = params; } Action addParam(String name, Object value) { if (value != null) { if (params == null) { params = new HashMap<>(); } params.put(name, value.toString()); } return this; } } private List<Action> stack = new ArrayList<>(); private List<Action> memory = new ArrayList<>(); private List<Action> storage = new ArrayList<>(); public List<Action> getStack() { return stack; } public void setStack(List<Action> stack) { this.stack = stack; } public List<Action> getMemory() { return memory; } public void setMemory(List<Action> memory) { this.memory = memory; } public List<Action> getStorage() { return storage; } public void setStorage(List<Action> storage) { this.storage = storage; } private static Action addAction(List<Action> container, Action.Name name) { Action action = new Action(); action.setName(name); container.add(action); return action; } public Action addStackPop() { return addAction(stack, Action.Name.pop); } public Action addStackPush(DataWord value) { return addAction(stack, Action.Name.push) .addParam("value", value); } public Action addStackSwap(int from, int to) { return addAction(stack, Action.Name.swap) .addParam("from", from) .addParam("to", to); } public Action addMemoryExtend(long delta) { return addAction(memory, Action.Name.extend) .addParam("delta", delta); } public Action addMemoryWrite(int address, byte[] data, int size) { return addAction(memory, Action.Name.write) .addParam("address", address) .addParam("data", toHexString(data).substring(0, size)); } public Action addStoragePut(DataWord key, DataWord value) { return addAction(storage, Action.Name.put) .addParam("key", key) .addParam("value", value); } public Action addStorageRemove(DataWord key) { return addAction(storage, Action.Name.remove) .addParam("key", key); } public Action addStorageClear() { return addAction(storage, Action.Name.clear); } }
4,179
26.142857
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/trace/ProgramTraceListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.listener.ProgramListenerAdaptor; public class ProgramTraceListener extends ProgramListenerAdaptor { private final boolean enabled; private OpActions actions = new OpActions(); public ProgramTraceListener(boolean enabled) { this.enabled = enabled; } @Override public void onMemoryExtend(int delta) { if (enabled) actions.addMemoryExtend(delta); } @Override public void onMemoryWrite(int address, byte[] data, int size) { if (enabled) actions.addMemoryWrite(address, data, size); } @Override public void onStackPop() { if (enabled) actions.addStackPop(); } @Override public void onStackPush(DataWord value) { if (enabled) actions.addStackPush(value); } @Override public void onStackSwap(int from, int to) { if (enabled) actions.addStackSwap(from, to); } @Override public void onStoragePut(DataWord key, DataWord value) { if (enabled) { if (value.equals(DataWord.ZERO)) { actions.addStorageRemove(key); } else { actions.addStoragePut(key, value); } } } @Override public void onStorageClear() { if (enabled) actions.addStorageClear(); } public OpActions resetActions() { OpActions actions = this.actions; this.actions = new OpActions(); return actions; } }
2,322
28.405063
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/trace/Op.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.trace; import org.ethereum.vm.OpCode; import java.math.BigInteger; public class Op { private OpCode code; private int deep; private int pc; private BigInteger gas; private OpActions actions; public OpCode getCode() { return code; } public void setCode(OpCode code) { this.code = code; } public int getDeep() { return deep; } public void setDeep(int deep) { this.deep = deep; } public int getPc() { return pc; } public void setPc(int pc) { this.pc = pc; } public BigInteger getGas() { return gas; } public void setGas(BigInteger gas) { this.gas = gas; } public OpActions getActions() { return actions; } public void setActions(OpActions actions) { this.actions = actions; } }
1,683
22.388889
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/ProgramResult.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.ethereum.util.ByteArraySet; import org.ethereum.vm.CallCreate; import org.ethereum.vm.DataWord; import org.ethereum.vm.LogInfo; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.apache.commons.collections4.CollectionUtils.isEmpty; import static org.apache.commons.collections4.CollectionUtils.size; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; /** * @author Roman Mandeleil * @since 07.06.2014 */ public class ProgramResult { private long gasUsed; private byte[] hReturn = EMPTY_BYTE_ARRAY; private RuntimeException exception; private boolean revert; private Set<DataWord> deleteAccounts; private ByteArraySet touchedAccounts = new ByteArraySet(); private List<InternalTransaction> internalTransactions; private List<LogInfo> logInfoList; private long futureRefund = 0; /* * for testing runs , * call/create is not executed * but dummy recorded */ private List<CallCreate> callCreateList; public void spendGas(long gas) { gasUsed += gas; } public void setRevert() { this.revert = true; } public boolean isRevert() { return revert; } public void refundGas(long gas) { gasUsed -= gas; } public void setHReturn(byte[] hReturn) { this.hReturn = hReturn; } public byte[] getHReturn() { return hReturn; } public RuntimeException getException() { return exception; } public long getGasUsed() { return gasUsed; } public void setException(RuntimeException exception) { this.exception = exception; } public Set<DataWord> getDeleteAccounts() { if (deleteAccounts == null) { deleteAccounts = new HashSet<>(); } return deleteAccounts; } public void addDeleteAccount(DataWord address) { getDeleteAccounts().add(address); } public void addDeleteAccounts(Set<DataWord> accounts) { if (!isEmpty(accounts)) { getDeleteAccounts().addAll(accounts); } } public void addTouchAccount(byte[] addr) { touchedAccounts.add(addr); } public Set<byte[]> getTouchedAccounts() { return touchedAccounts; } public void addTouchAccounts(Set<byte[]> accounts) { if (!isEmpty(accounts)) { getTouchedAccounts().addAll(accounts); } } public List<LogInfo> getLogInfoList() { if (logInfoList == null) { logInfoList = new ArrayList<>(); } return logInfoList; } public void addLogInfo(LogInfo logInfo) { getLogInfoList().add(logInfo); } public void addLogInfos(List<LogInfo> logInfos) { if (!isEmpty(logInfos)) { getLogInfoList().addAll(logInfos); } } public List<CallCreate> getCallCreateList() { if (callCreateList == null) { callCreateList = new ArrayList<>(); } return callCreateList; } public void addCallCreate(byte[] data, byte[] destination, byte[] gasLimit, byte[] value) { getCallCreateList().add(new CallCreate(data, destination, gasLimit, value)); } public List<InternalTransaction> getInternalTransactions() { if (internalTransactions == null) { internalTransactions = new ArrayList<>(); } return internalTransactions; } public InternalTransaction addInternalTransaction(byte[] parentHash, int deep, byte[] nonce, DataWord gasPrice, DataWord gasLimit, byte[] senderAddress, byte[] receiveAddress, byte[] value, byte[] data, String note) { InternalTransaction transaction = new InternalTransaction(parentHash, deep, size(internalTransactions), nonce, gasPrice, gasLimit, senderAddress, receiveAddress, value, data, note); getInternalTransactions().add(transaction); return transaction; } public void addInternalTransactions(List<InternalTransaction> internalTransactions) { getInternalTransactions().addAll(internalTransactions); } public void rejectInternalTransactions() { for (InternalTransaction internalTx : getInternalTransactions()) { internalTx.reject(); } } public void addFutureRefund(long gasValue) { futureRefund += gasValue; } public long getFutureRefund() { return futureRefund; } public void resetFutureRefund() { futureRefund = 0; } public void merge(ProgramResult another) { addInternalTransactions(another.getInternalTransactions()); if (another.getException() == null && !another.isRevert()) { addDeleteAccounts(another.getDeleteAccounts()); addLogInfos(another.getLogInfoList()); addFutureRefund(another.getFutureRefund()); addTouchAccounts(another.getTouchedAccounts()); } } public static ProgramResult createEmpty() { ProgramResult result = new ProgramResult(); result.setHReturn(EMPTY_BYTE_ARRAY); return result; } }
6,038
28.315534
189
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/ProgramPrecompile.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.ethereum.datasource.Source; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; import org.ethereum.vm.OpCode; import java.util.HashSet; import java.util.Set; /** * Created by Anton Nashatyrev on 06.02.2017. */ public class ProgramPrecompile { private static final int version = 1; private Set<Integer> jumpdest = new HashSet<>(); public byte[] serialize() { byte[][] jdBytes = new byte[jumpdest.size() + 1][]; int cnt = 0; jdBytes[cnt++] = RLP.encodeInt(version); for (Integer dst : jumpdest) { jdBytes[cnt++] = RLP.encodeInt(dst); } return RLP.encodeList(jdBytes); } public static ProgramPrecompile deserialize(byte[] stream) { RLPList l = (RLPList) RLP.decode2(stream).get(0); int ver = ByteUtil.byteArrayToInt(l.get(0).getRLPData()); if (ver != version) return null; ProgramPrecompile ret = new ProgramPrecompile(); for (int i = 1; i < l.size(); i++) { ret.jumpdest.add(ByteUtil.byteArrayToInt(l.get(i).getRLPData())); } return ret; } public static ProgramPrecompile compile(byte[] ops) { ProgramPrecompile ret = new ProgramPrecompile(); for (int i = 0; i < ops.length; ++i) { OpCode op = OpCode.code(ops[i]); if (op == null) continue; if (op.equals(OpCode.JUMPDEST)) ret.jumpdest.add(i); if (op.asInt() >= OpCode.PUSH1.asInt() && op.asInt() <= OpCode.PUSH32.asInt()) { i += op.asInt() - OpCode.PUSH1.asInt() + 1; } } return ret; } public boolean hasJumpDest(int pc) { return jumpdest.contains(pc); } public static void main(String[] args) throws Exception { ProgramPrecompile pp = new ProgramPrecompile(); pp.jumpdest.add(100); pp.jumpdest.add(200); byte[] bytes = pp.serialize(); ProgramPrecompile pp1 = ProgramPrecompile.deserialize(bytes); System.out.println(pp1.jumpdest); } }
2,960
31.9
92
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/Storage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.ethereum.core.AccountState; import org.ethereum.core.Block; import org.ethereum.core.Repository; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.db.ContractDetails; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.invoke.ProgramInvoke; import org.ethereum.vm.program.listener.ProgramListener; import org.ethereum.vm.program.listener.ProgramListenerAware; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Storage implements Repository, ProgramListenerAware { private final Repository repository; private final DataWord address; private ProgramListener programListener; public Storage(ProgramInvoke programInvoke) { this.address = programInvoke.getOwnerAddress(); this.repository = programInvoke.getRepository(); } private Storage(Repository repository, DataWord address) { this.repository = repository; this.address = address; } @Override public void setProgramListener(ProgramListener listener) { this.programListener = listener; } @Override public AccountState createAccount(byte[] addr) { return repository.createAccount(addr); } @Override public boolean isExist(byte[] addr) { return repository.isExist(addr); } @Override public AccountState getAccountState(byte[] addr) { return repository.getAccountState(addr); } @Override public void delete(byte[] addr) { if (canListenTrace(addr)) programListener.onStorageClear(); repository.delete(addr); } @Override public BigInteger increaseNonce(byte[] addr) { return repository.increaseNonce(addr); } @Override public BigInteger setNonce(byte[] addr, BigInteger nonce) { return repository.setNonce(addr, nonce); } @Override public BigInteger getNonce(byte[] addr) { return repository.getNonce(addr); } @Override public ContractDetails getContractDetails(byte[] addr) { return repository.getContractDetails(addr); } @Override public boolean hasContractDetails(byte[] addr) { return repository.hasContractDetails(addr); } @Override public void saveCode(byte[] addr, byte[] code) { repository.saveCode(addr, code); } @Override public byte[] getCode(byte[] addr) { return repository.getCode(addr); } @Override public byte[] getCodeHash(byte[] addr) { return repository.getCodeHash(addr); } @Override public void addStorageRow(byte[] addr, DataWord key, DataWord value) { if (canListenTrace(addr)) programListener.onStoragePut(key, value); repository.addStorageRow(addr, key, value); } private boolean canListenTrace(byte[] address) { return (programListener != null) && this.address.equals(DataWord.of(address)); } @Override public DataWord getStorageValue(byte[] addr, DataWord key) { return repository.getStorageValue(addr, key); } @Override public BigInteger getBalance(byte[] addr) { return repository.getBalance(addr); } @Override public BigInteger addBalance(byte[] addr, BigInteger value) { return repository.addBalance(addr, value); } @Override public Set<byte[]> getAccountsKeys() { return repository.getAccountsKeys(); } @Override public void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash) { repository.dumpState(block, gasUsed, txNumber, txHash); } @Override public Repository startTracking() { return repository.startTracking(); } @Override public void flush() { repository.flush(); } @Override public void flushNoReconnect() { throw new UnsupportedOperationException(); } @Override public void commit() { repository.commit(); } @Override public void rollback() { repository.rollback(); } @Override public void syncToRoot(byte[] root) { repository.syncToRoot(root); } @Override public boolean isClosed() { return repository.isClosed(); } @Override public void close() { repository.close(); } @Override public void reset() { repository.reset(); } @Override public void updateBatch(HashMap<ByteArrayWrapper, AccountState> accountStates, HashMap<ByteArrayWrapper, ContractDetails> contractDetails) { for (ByteArrayWrapper address : contractDetails.keySet()) { if (!canListenTrace(address.getData())) return; ContractDetails details = contractDetails.get(address); if (details.isDeleted()) { programListener.onStorageClear(); } else if (details.isDirty()) { for (Map.Entry<DataWord, DataWord> entry : details.getStorage().entrySet()) { programListener.onStoragePut(entry.getKey(), entry.getValue()); } } } repository.updateBatch(accountStates, contractDetails); } @Override public byte[] getRoot() { return repository.getRoot(); } @Override public void loadAccount(byte[] addr, HashMap<ByteArrayWrapper, AccountState> cacheAccounts, HashMap<ByteArrayWrapper, ContractDetails> cacheDetails) { repository.loadAccount(addr, cacheAccounts, cacheDetails); } @Override public Repository getSnapshotTo(byte[] root) { throw new UnsupportedOperationException(); } @Override public Repository clone() { return new Storage(repository.getSnapshotTo(getRoot()), address); } @Override public int getStorageSize(byte[] addr) { return repository.getStorageSize(addr); } @Override public Set<DataWord> getStorageKeys(byte[] addr) { return repository.getStorageKeys(addr); } @Override public Map<DataWord, DataWord> getStorage(byte[] addr, @Nullable Collection<DataWord> keys) { return repository.getStorage(addr, keys); } }
7,066
27.043651
154
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/Program.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.BlockchainConfig; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.core.AccountState; import org.ethereum.core.Repository; import org.ethereum.core.Transaction; import org.ethereum.crypto.HashUtil; import org.ethereum.db.ContractDetails; import org.ethereum.util.ByteArraySet; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.ethereum.util.Utils; import org.ethereum.vm.*; import org.ethereum.vm.PrecompiledContracts.PrecompiledContract; import org.ethereum.vm.hook.VMHook; import org.ethereum.vm.program.invoke.ProgramInvoke; import org.ethereum.vm.program.invoke.ProgramInvokeFactory; import org.ethereum.vm.program.invoke.ProgramInvokeFactoryImpl; import org.ethereum.vm.program.listener.CompositeProgramListener; import org.ethereum.vm.program.listener.ProgramListenerAware; import org.ethereum.vm.program.listener.ProgramStorageChangeListener; import org.ethereum.vm.trace.ProgramTraceListener; import org.ethereum.vm.trace.ProgramTrace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.util.*; import static java.lang.StrictMath.min; import static java.lang.String.format; import static java.math.BigInteger.ZERO; import static org.apache.commons.lang3.ArrayUtils.*; import static org.ethereum.util.BIUtil.*; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; import static org.ethereum.util.ByteUtil.toHexString; /** * @author Roman Mandeleil * @since 01.06.2014 */ public class Program { private static final Logger logger = LoggerFactory.getLogger("VM"); /** * This attribute defines the number of recursive calls allowed in the EVM * Note: For the JVM to reach this level without a StackOverflow exception, * ethereumj may need to be started with a JVM argument to increase * the stack size. For example: -Xss10m */ private static final int MAX_DEPTH = 1024; //Max size for stack checks private static final int MAX_STACKSIZE = 1024; private Transaction transaction; private ProgramInvoke invoke; private ProgramInvokeFactory programInvokeFactory = new ProgramInvokeFactoryImpl(); private ProgramOutListener listener; private ProgramTraceListener traceListener; private ProgramStorageChangeListener storageDiffListener = new ProgramStorageChangeListener(); private CompositeProgramListener programListener = new CompositeProgramListener(); private Stack stack; private Memory memory; private Storage storage; private Repository originalRepo; private byte[] returnDataBuffer; private ProgramResult result = new ProgramResult(); private ProgramTrace trace = new ProgramTrace(); private byte[] codeHash; private byte[] ops; private int pc; private byte lastOp; private byte previouslyExecutedOp; private boolean stopped; private ByteArraySet touchedAccounts = new ByteArraySet(); private ProgramPrecompile programPrecompile; CommonConfig commonConfig = CommonConfig.getDefault(); private final SystemProperties config; private final BlockchainConfig blockchainConfig; private final VMHook vmHook; public Program(byte[] ops, ProgramInvoke programInvoke) { this(ops, programInvoke, (Transaction) null); } public Program(byte[] ops, ProgramInvoke programInvoke, SystemProperties config) { this(ops, programInvoke, null, config, VMHook.EMPTY); } public Program(byte[] ops, ProgramInvoke programInvoke, Transaction transaction) { this(ops, programInvoke, transaction, SystemProperties.getDefault(), VMHook.EMPTY); } public Program(byte[] ops, ProgramInvoke programInvoke, Transaction transaction, SystemProperties config, VMHook vmHook) { this(null, ops, programInvoke, transaction, config, vmHook); } public Program(byte[] codeHash, byte[] ops, ProgramInvoke programInvoke, Transaction transaction, SystemProperties config, VMHook vmHook) { this.config = config; this.invoke = programInvoke; this.transaction = transaction; this.codeHash = codeHash == null || FastByteComparisons.equal(HashUtil.EMPTY_DATA_HASH, codeHash) ? null : codeHash; this.ops = nullToEmpty(ops); this.vmHook = vmHook; this.traceListener = new ProgramTraceListener(config.vmTrace()); this.memory = setupProgramListener(new Memory()); this.stack = setupProgramListener(new Stack()); this.originalRepo = programInvoke.getOrigRepository(); this.storage = setupProgramListener(new Storage(programInvoke)); this.trace = new ProgramTrace(config, programInvoke); this.blockchainConfig = config.getBlockchainConfig().getConfigForBlock(programInvoke.getNumber().longValue()); } public ProgramPrecompile getProgramPrecompile() { if (programPrecompile == null) { if (codeHash != null && commonConfig.precompileSource() != null) { programPrecompile = commonConfig.precompileSource().get(codeHash); } if (programPrecompile == null) { programPrecompile = ProgramPrecompile.compile(ops); if (codeHash != null && commonConfig.precompileSource() != null) { commonConfig.precompileSource().put(codeHash, programPrecompile); } } } return programPrecompile; } public Program withCommonConfig(CommonConfig commonConfig) { this.commonConfig = commonConfig; return this; } public int getCallDeep() { return invoke.getCallDeep(); } private InternalTransaction addInternalTx(byte[] nonce, DataWord gasLimit, byte[] senderAddress, byte[] receiveAddress, BigInteger value, byte[] data, String note) { InternalTransaction result = null; if (transaction != null) { byte[] senderNonce = isEmpty(nonce) ? getStorage().getNonce(senderAddress).toByteArray() : nonce; data = config.recordInternalTransactionsData() ? data : null; result = getResult().addInternalTransaction(transaction.getHash(), getCallDeep(), senderNonce, getGasPrice(), gasLimit, senderAddress, receiveAddress, value.toByteArray(), data, note); } return result; } private <T extends ProgramListenerAware> T setupProgramListener(T programListenerAware) { if (programListener.isEmpty()) { programListener.addListener(traceListener); programListener.addListener(storageDiffListener); } programListenerAware.setProgramListener(programListener); return programListenerAware; } public Map<DataWord, DataWord> getStorageDiff() { return storageDiffListener.getDiff(); } public byte getOp(int pc) { return (getLength(ops) <= pc) ? 0 : ops[pc]; } public byte getCurrentOp() { return isEmpty(ops) ? 0 : ops[pc]; } /** * Last Op can only be set publicly (no getLastOp method), is used for logging. */ public void setLastOp(byte op) { this.lastOp = op; } /** * Should be set only after the OP is fully executed. */ public void setPreviouslyExecutedOp(byte op) { this.previouslyExecutedOp = op; } /** * Returns the last fully executed OP. */ public byte getPreviouslyExecutedOp() { return this.previouslyExecutedOp; } public void stackPush(byte[] data) { stackPush(DataWord.of(data)); } public void stackPushZero() { stackPush(DataWord.ZERO); } public void stackPushOne() { DataWord stackWord = DataWord.ONE; stackPush(stackWord); } public void stackPush(DataWord stackWord) { verifyStackOverflow(0, 1); //Sanity Check stack.push(stackWord); } public Stack getStack() { return this.stack; } public int getPC() { return pc; } public void setPC(DataWord pc) { this.setPC(pc.intValue()); } public void setPC(int pc) { this.pc = pc; if (this.pc >= ops.length) { stop(); } } public boolean isStopped() { return stopped; } public void stop() { stopped = true; } public void setHReturn(byte[] buff) { getResult().setHReturn(buff); } public void step() { setPC(pc + 1); } public byte[] sweep(int n) { if (pc + n > ops.length) stop(); byte[] data = Arrays.copyOfRange(ops, pc, pc + n); pc += n; if (pc >= ops.length) stop(); return data; } public DataWord stackPop() { return stack.pop(); } /** * Verifies that the stack is at least <code>stackSize</code> * * @param stackSize int * @throws StackTooSmallException If the stack is * smaller than <code>stackSize</code> */ public void verifyStackSize(int stackSize) { if (stack.size() < stackSize) { throw Program.Exception.tooSmallStack(stackSize, stack.size()); } } public void verifyStackOverflow(int argsReqs, int returnReqs) { if ((stack.size() - argsReqs + returnReqs) > MAX_STACKSIZE) { throw new StackTooLargeException("Expected: overflow " + MAX_STACKSIZE + " elements stack limit"); } } public int getMemSize() { return memory.size(); } public void memorySave(DataWord addrB, DataWord value) { memory.write(addrB.intValue(), value.getData(), value.getData().length, false); } public void memorySaveLimited(int addr, byte[] data, int dataSize) { memory.write(addr, data, dataSize, true); } public void memorySave(int addr, byte[] value) { memory.write(addr, value, value.length, false); } public void memoryExpand(DataWord outDataOffs, DataWord outDataSize) { if (!outDataSize.isZero()) { memory.extend(outDataOffs.intValue(), outDataSize.intValue()); } } /** * Allocates a piece of memory and stores value at given offset address * * @param addr is the offset address * @param allocSize size of memory needed to write * @param value the data to write to memory */ public void memorySave(int addr, int allocSize, byte[] value) { memory.extendAndWrite(addr, allocSize, value); } public DataWord memoryLoad(DataWord addr) { return memory.readWord(addr.intValue()); } public DataWord memoryLoad(int address) { return memory.readWord(address); } public byte[] memoryChunk(int offset, int size) { return memory.read(offset, size); } /** * Allocates extra memory in the program for * a specified size, calculated from a given offset * * @param offset the memory address offset * @param size the number of bytes to allocate */ public void allocateMemory(int offset, int size) { memory.extend(offset, size); } public void suicide(DataWord obtainerAddress) { byte[] owner = getOwnerAddress().getLast20Bytes(); byte[] obtainer = obtainerAddress.getLast20Bytes(); BigInteger balance = getStorage().getBalance(owner); if (logger.isInfoEnabled()) logger.info("Transfer to: [{}] heritage: [{}]", toHexString(obtainer), balance); addInternalTx(null, null, owner, obtainer, balance, null, "suicide"); if (FastByteComparisons.compareTo(owner, 0, 20, obtainer, 0, 20) == 0) { // if owner == obtainer just zeroing account according to Yellow Paper getStorage().addBalance(owner, balance.negate()); } else { transfer(getStorage(), owner, obtainer, balance); } getResult().addDeleteAccount(this.getOwnerAddress()); } public Repository getStorage() { return this.storage; } /** * Create contract for {@link OpCode#CREATE} * @param value Endowment * @param memStart Code memory offset * @param memSize Code memory size */ public void createContract(DataWord value, DataWord memStart, DataWord memSize) { returnDataBuffer = null; // reset return buffer right before the call byte[] senderAddress = this.getOwnerAddress().getLast20Bytes(); BigInteger endowment = value.value(); if (!verifyCall(senderAddress, endowment)) return; byte[] nonce = getStorage().getNonce(senderAddress).toByteArray(); byte[] contractAddress = HashUtil.calcNewAddr(senderAddress, nonce); byte[] programCode = memoryChunk(memStart.intValue(), memSize.intValue()); createContractImpl(value, programCode, contractAddress); } /** * Create contract for {@link OpCode#CREATE2} * @param value Endowment * @param memStart Code memory offset * @param memSize Code memory size * @param salt Salt, used in contract address calculation */ public void createContract2(DataWord value, DataWord memStart, DataWord memSize, DataWord salt) { returnDataBuffer = null; // reset return buffer right before the call byte[] senderAddress = this.getOwnerAddress().getLast20Bytes(); BigInteger endowment = value.value(); if (!verifyCall(senderAddress, endowment)) return; byte[] programCode = memoryChunk(memStart.intValue(), memSize.intValue()); byte[] contractAddress = HashUtil.calcSaltAddr(senderAddress, programCode, salt.getData()); createContractImpl(value, programCode, contractAddress); } /** * Verifies CREATE attempt */ private boolean verifyCall(byte[] senderAddress, BigInteger endowment) { if (getCallDeep() == MAX_DEPTH) { stackPushZero(); return false; } if (isNotCovers(getStorage().getBalance(senderAddress), endowment)) { stackPushZero(); return false; } return true; } /** * All stages required to create contract on provided address after initial check * @param value Endowment * @param programCode Contract code * @param newAddress Contract address */ @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private void createContractImpl(DataWord value, byte[] programCode, byte[] newAddress) { // [1] LOG, SPEND GAS byte[] senderAddress = this.getOwnerAddress().getLast20Bytes(); if (logger.isInfoEnabled()) logger.info("creating a new contract inside contract run: [{}]", toHexString(senderAddress)); BlockchainConfig blockchainConfig = config.getBlockchainConfig().getConfigForBlock(getNumber().longValue()); // actual gas subtract DataWord gasLimit = blockchainConfig.getCreateGas(getGas()); spendGas(gasLimit.longValue(), "internal call"); // [2] CREATE THE CONTRACT ADDRESS AccountState existingAddr = getStorage().getAccountState(newAddress); boolean contractAlreadyExists = existingAddr != null && existingAddr.isContractExist(blockchainConfig); if (byTestingSuite()) { // This keeps track of the contracts created for a test getResult().addCallCreate(programCode, EMPTY_BYTE_ARRAY, gasLimit.getNoLeadZeroesData(), value.getNoLeadZeroesData()); } // [3] UPDATE THE NONCE // (THIS STAGE IS NOT REVERTED BY ANY EXCEPTION) if (!byTestingSuite()) { getStorage().increaseNonce(senderAddress); } Repository track = getStorage().startTracking(); //In case of hashing collisions, check for any balance before createAccount() BigInteger oldBalance = track.getBalance(newAddress); track.createAccount(newAddress); if (blockchainConfig.eip161()) { track.increaseNonce(newAddress); } track.addBalance(newAddress, oldBalance); // [4] TRANSFER THE BALANCE BigInteger endowment = value.value(); BigInteger newBalance = ZERO; if (!byTestingSuite()) { track.addBalance(senderAddress, endowment.negate()); newBalance = track.addBalance(newAddress, endowment); } // [5] COOK THE INVOKE AND EXECUTE byte[] nonce = getStorage().getNonce(senderAddress).toByteArray(); InternalTransaction internalTx = addInternalTx(nonce, getGasLimit(), senderAddress, null, endowment, programCode, "create"); Repository originalRepo = this.invoke.getOrigRepository(); // Some TCK tests have storage only addresses (no code, zero nonce etc) - impossible situation in the real network // So, we should clean up it before reuse, but as tx not always goes successful, state should be correctly // reverted in that case too if (!contractAlreadyExists && track.hasContractDetails(newAddress)) { originalRepo = originalRepo.clone(); originalRepo.delete(newAddress); } ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke( this, DataWord.of(newAddress), getOwnerAddress(), value, gasLimit, newBalance, null, track, originalRepo, this.invoke.getBlockStore(), false, byTestingSuite()); ProgramResult result = ProgramResult.createEmpty(); if (contractAlreadyExists) { result.setException(new BytecodeExecutionException("Trying to create a contract with existing contract address: 0x" + toHexString(newAddress))); } else if (isNotEmpty(programCode)) { VM vm = new VM(config, vmHook); Program program = new Program(programCode, programInvoke, internalTx, config, vmHook).withCommonConfig(commonConfig); // reset storage if the contract with the same address already exists // TCK test case only - normally this is near-impossible situation in the real network ContractDetails contractDetails = program.getStorage().getContractDetails(newAddress); contractDetails.deleteStorage(); vm.play(program); result = program.getResult(); } // 4. CREATE THE CONTRACT OUT OF RETURN if (!result.isRevert() && result.getException() == null) { byte[] code = result.getHReturn(); long storageCost = getLength(code) * getBlockchainConfig().getGasCost().getCREATE_DATA(); long afterSpend = programInvoke.getGas().longValue() - result.getGasUsed() - storageCost; if (afterSpend < 0) { if (!blockchainConfig.getConstants().createEmptyContractOnOOG()) { result.setException(Program.Exception.notEnoughSpendingGas("No gas to return just created contract", storageCost, this)); } else { track.saveCode(newAddress, EMPTY_BYTE_ARRAY); } } else if (getLength(code) > blockchainConfig.getConstants().getMAX_CONTRACT_SZIE()) { result.setException(Program.Exception.notEnoughSpendingGas("Contract size too large: " + getLength(result.getHReturn()), storageCost, this)); } else { result.spendGas(storageCost); track.saveCode(newAddress, code); } } getResult().merge(result); if (result.getException() != null || result.isRevert()) { logger.debug("contract run halted by Exception: contract: [{}], exception: [{}]", toHexString(newAddress), result.getException()); internalTx.reject(); result.rejectInternalTransactions(); track.rollback(); stackPushZero(); if (result.getException() != null) { return; } else { returnDataBuffer = result.getHReturn(); } } else { if (!byTestingSuite()) track.commit(); // IN SUCCESS PUSH THE ADDRESS INTO THE STACK stackPush(DataWord.of(newAddress)); } // 5. REFUND THE REMAIN GAS long refundGas = gasLimit.longValue() - result.getGasUsed(); if (refundGas > 0) { refundGas(refundGas, "remain gas from the internal call"); if (logger.isInfoEnabled()) { logger.info("The remaining gas is refunded, account: [{}], gas: [{}] ", toHexString(getOwnerAddress().getLast20Bytes()), refundGas); } } touchedAccounts.add(newAddress); } /** * That method is for internal code invocations * <p/> * - Normal calls invoke a specified contract which updates itself * - Stateless calls invoke code from another contract, within the context of the caller * * @param msg is the message call object */ public void callToAddress(MessageCall msg) { returnDataBuffer = null; // reset return buffer right before the call if (getCallDeep() == MAX_DEPTH) { stackPushZero(); refundGas(msg.getGas().longValue(), " call deep limit reach"); return; } byte[] data = memoryChunk(msg.getInDataOffs().intValue(), msg.getInDataSize().intValue()); // FETCH THE SAVED STORAGE byte[] codeAddress = msg.getCodeAddress().getLast20Bytes(); byte[] senderAddress = getOwnerAddress().getLast20Bytes(); byte[] contextAddress = msg.getType().callIsStateless() ? senderAddress : codeAddress; if (logger.isInfoEnabled()) logger.info(msg.getType().name() + " for existing contract: address: [{}], outDataOffs: [{}], outDataSize: [{}] ", toHexString(contextAddress), msg.getOutDataOffs().longValue(), msg.getOutDataSize().longValue()); Repository track = getStorage().startTracking(); // 2.1 PERFORM THE VALUE (endowment) PART BigInteger endowment = msg.getEndowment().value(); BigInteger senderBalance = track.getBalance(senderAddress); if (isNotCovers(senderBalance, endowment)) { stackPushZero(); refundGas(msg.getGas().longValue(), "refund gas from message call"); return; } // FETCH THE CODE byte[] programCode = getStorage().isExist(codeAddress) ? getStorage().getCode(codeAddress) : EMPTY_BYTE_ARRAY; BigInteger contextBalance = ZERO; if (byTestingSuite()) { // This keeps track of the calls created for a test getResult().addCallCreate(data, contextAddress, msg.getGas().getNoLeadZeroesData(), msg.getEndowment().getNoLeadZeroesData()); } else { track.addBalance(senderAddress, endowment.negate()); contextBalance = track.addBalance(contextAddress, endowment); } // CREATE CALL INTERNAL TRANSACTION InternalTransaction internalTx = addInternalTx(null, getGasLimit(), senderAddress, contextAddress, endowment, data, "call"); ProgramResult result = null; if (isNotEmpty(programCode)) { ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke( this, DataWord.of(contextAddress), msg.getType().callIsDelegate() ? getCallerAddress() : getOwnerAddress(), msg.getType().callIsDelegate() ? getCallValue() : msg.getEndowment(), msg.getGas(), contextBalance, data, track, this.invoke.getOrigRepository(), this.invoke.getBlockStore(), msg.getType().callIsStatic() || isStaticCall(), byTestingSuite()); VM vm = new VM(config, vmHook); Program program = new Program(getStorage().getCodeHash(codeAddress), programCode, programInvoke, internalTx, config, vmHook) .withCommonConfig(commonConfig); vm.play(program); result = program.getResult(); getTrace().merge(program.getTrace()); getResult().merge(result); if (result.getException() != null || result.isRevert()) { logger.debug("contract run halted by Exception: contract: [{}], exception: [{}]", toHexString(contextAddress), result.getException()); internalTx.reject(); result.rejectInternalTransactions(); track.rollback(); stackPushZero(); if (result.getException() != null) { return; } } else { // 4. THE FLAG OF SUCCESS IS ONE PUSHED INTO THE STACK track.commit(); stackPushOne(); } if (byTestingSuite()) { logger.info("Testing run, skipping storage diff listener"); } else if (Arrays.equals(transaction.getReceiveAddress(), internalTx.getReceiveAddress())) { storageDiffListener.merge(program.getStorageDiff()); } } else { // 4. THE FLAG OF SUCCESS IS ONE PUSHED INTO THE STACK track.commit(); stackPushOne(); } // 3. APPLY RESULTS: result.getHReturn() into out_memory allocated if (result != null) { byte[] buffer = result.getHReturn(); int offset = msg.getOutDataOffs().intValue(); int size = msg.getOutDataSize().intValue(); memorySaveLimited(offset, buffer, size); returnDataBuffer = buffer; } // 5. REFUND THE REMAIN GAS if (result != null) { BigInteger refundGas = msg.getGas().value().subtract(toBI(result.getGasUsed())); if (isPositive(refundGas)) { refundGas(refundGas.longValue(), "remaining gas from the internal call"); if (logger.isInfoEnabled()) logger.info("The remaining gas refunded, account: [{}], gas: [{}] ", toHexString(senderAddress), refundGas.toString()); } } else { refundGas(msg.getGas().longValue(), "remaining gas from the internal call"); } } public void spendGas(long gasValue, String cause) { if (logger.isDebugEnabled()) { logger.debug("[{}] Spent for cause: [{}], gas: [{}]", invoke.hashCode(), cause, gasValue); } if (getGasLong() < gasValue) { throw Program.Exception.notEnoughSpendingGas(cause, gasValue, this); } getResult().spendGas(gasValue); } public void spendAllGas() { spendGas(getGas().longValue(), "Spending all remaining"); } public void refundGas(long gasValue, String cause) { logger.info("[{}] Refund for cause: [{}], gas: [{}]", invoke.hashCode(), cause, gasValue); getResult().refundGas(gasValue); } public void futureRefundGas(long gasValue) { logger.info("Future refund added: [{}]", gasValue); getResult().addFutureRefund(gasValue); } public void resetFutureRefund() { getResult().resetFutureRefund(); } public void storageSave(DataWord word1, DataWord word2) { storageSave(word1.getData(), word2.getData()); } public void storageSave(byte[] key, byte[] val) { DataWord keyWord = DataWord.of(key); DataWord valWord = DataWord.of(val); getStorage().addStorageRow(getOwnerAddress().getLast20Bytes(), keyWord, valWord); } public byte[] getCode() { return ops; } public byte[] getCodeAt(DataWord address) { byte[] code = invoke.getRepository().getCode(address.getLast20Bytes()); return nullToEmpty(code); } public byte[] getCodeHashAt(DataWord address) { AccountState state = invoke.getRepository().getAccountState(address.getLast20Bytes()); // return 0 as a code hash of empty account (an account that would be removed by state clearing) if (state != null && state.isEmpty()) { return EMPTY_BYTE_ARRAY; } else { byte[] code = invoke.getRepository().getCodeHash(address.getLast20Bytes()); return nullToEmpty(code); } } public DataWord getOwnerAddress() { return invoke.getOwnerAddress(); } public DataWord getBlockHash(int index) { return index < this.getNumber().longValue() && index >= Math.max(256, this.getNumber().intValue()) - 256 ? DataWord.of(this.invoke.getBlockStore().getBlockHashByNumber(index, getPrevHash().getData())) : DataWord.ZERO; } public DataWord getBalance(DataWord address) { BigInteger balance = getStorage().getBalance(address.getLast20Bytes()); return DataWord.of(balance.toByteArray()); } public DataWord getOriginAddress() { return invoke.getOriginAddress(); } public DataWord getCallerAddress() { return invoke.getCallerAddress(); } public DataWord getGasPrice() { return invoke.getMinGasPrice(); } public long getGasLong() { return invoke.getGasLong() - getResult().getGasUsed(); } public DataWord getGas() { return DataWord.of(invoke.getGasLong() - getResult().getGasUsed()); } public DataWord getCallValue() { return invoke.getCallValue(); } public DataWord getDataSize() { return invoke.getDataSize(); } public DataWord getDataValue(DataWord index) { return invoke.getDataValue(index); } public byte[] getDataCopy(DataWord offset, DataWord length) { return invoke.getDataCopy(offset, length); } public DataWord getReturnDataBufferSize() { return DataWord.of(getReturnDataBufferSizeI()); } private int getReturnDataBufferSizeI() { return returnDataBuffer == null ? 0 : returnDataBuffer.length; } public byte[] getReturnDataBufferData(DataWord off, DataWord size) { if ((long) off.intValueSafe() + size.intValueSafe() > getReturnDataBufferSizeI()) return null; return returnDataBuffer == null ? new byte[0] : Arrays.copyOfRange(returnDataBuffer, off.intValueSafe(), off.intValueSafe() + size.intValueSafe()); } public DataWord storageLoad(DataWord key) { return getStorage().getStorageValue(getOwnerAddress().getLast20Bytes(), key); } /** * @return current Storage data for key */ public DataWord getCurrentValue(DataWord key) { return getStorage().getStorageValue(getOwnerAddress().getLast20Bytes(), key); } /* * Original storage value at the beginning of current frame execution * For more info check EIP-1283 https://eips.ethereum.org/EIPS/eip-1283 * @return Storage data at the beginning of Program execution */ public DataWord getOriginalValue(DataWord key) { return originalRepo.getStorageValue(getOwnerAddress().getLast20Bytes(), key); } public DataWord getPrevHash() { return invoke.getPrevHash(); } public DataWord getCoinbase() { return invoke.getCoinbase(); } public DataWord getTimestamp() { return invoke.getTimestamp(); } public DataWord getNumber() { return invoke.getNumber(); } public BlockchainConfig getBlockchainConfig() { return blockchainConfig; } public DataWord getDifficulty() { return invoke.getDifficulty(); } public DataWord getGasLimit() { return invoke.getGaslimit(); } public boolean isStaticCall() { return invoke.isStaticCall(); } public ProgramResult getResult() { return result; } public void setRuntimeFailure(RuntimeException e) { getResult().setException(e); } public String memoryToString() { return memory.toString(); } public void fullTrace() { if (logger.isTraceEnabled() || listener != null) { 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"); ContractDetails contractDetails = getStorage(). getContractDetails(getOwnerAddress().getLast20Bytes()); StringBuilder storageData = new StringBuilder(); if (contractDetails != null) { try { List<DataWord> storageKeys = new ArrayList<>(contractDetails.getStorage().keySet()); Collections.sort(storageKeys); for (DataWord key : storageKeys) { storageData.append(" ").append(key).append(" -> "). append(contractDetails.getStorage().get(key)).append("\n"); } if (storageData.length() > 0) storageData.insert(0, "\n"); } catch (java.lang.Exception e) { storageData.append("Failed to print storage: ").append(e.getMessage()); } } StringBuilder memoryData = new StringBuilder(); StringBuilder oneLine = new StringBuilder(); if (memory.size() > 320) memoryData.append("... Memory Folded.... ") .append("(") .append(memory.size()) .append(") bytes"); else for (int i = 0; i < memory.size(); ++i) { byte value = memory.readByte(i); oneLine.append(ByteUtil.oneByteToHexString(value)).append(" "); if ((i + 1) % 16 == 0) { String tmp = 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.size()) 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.trace(" -- OPS -- {}", opsString); logger.trace(" -- STACK -- {}", stackData); logger.trace(" -- MEMORY -- {}", memoryData); logger.trace(" -- STORAGE -- {}\n", storageData); logger.trace("\n Spent Gas: [{}]/[{}]\n Left Gas: [{}]\n", getResult().getGasUsed(), invoke.getGas().longValue(), getGas().longValue()); StringBuilder globalOutput = new StringBuilder("\n"); if (stackData.length() > 0) stackData.append("\n"); if (pc != 0) globalOutput.append("[Op: ").append(OpCode.code(lastOp).name()).append("]\n"); globalOutput.append(" -- OPS -- ").append(opsString).append("\n"); globalOutput.append(" -- STACK -- ").append(stackData).append("\n"); globalOutput.append(" -- MEMORY -- ").append(memoryData).append("\n"); globalOutput.append(" -- STORAGE -- ").append(storageData).append("\n"); if (getResult().getHReturn() != null) globalOutput.append("\n HReturn: ").append( Hex.toHexString(getResult().getHReturn())); // sophisticated assumption that msg.data != codedata // means we are calling the contract not creating it byte[] txData = invoke.getDataCopy(DataWord.ZERO, getDataSize()); if (!Arrays.equals(txData, ops)) globalOutput.append("\n msg.data: ").append(Hex.toHexString(txData)); globalOutput.append("\n\n Spent Gas: ").append(getResult().getGasUsed()); if (listener != null) listener.output(globalOutput.toString()); } } public void saveOpTrace() { if (this.pc < ops.length) { trace.addOp(ops[pc], pc, getCallDeep(), getGas(), traceListener.resetActions()); } } public ProgramTrace getTrace() { return trace; } static String formatBinData(byte[] binData, int startPC) { StringBuilder ret = new StringBuilder(); for (int i = 0; i < binData.length; i += 16) { ret.append(Utils.align("" + Integer.toHexString(startPC + (i)) + ":", ' ', 8, false)); ret.append(Hex.toHexString(binData, i, min(16, binData.length - i))).append('\n'); } return ret.toString(); } public static String stringifyMultiline(byte[] code) { int index = 0; StringBuilder sb = new StringBuilder(); BitSet mask = buildReachableBytecodesMask(code); ByteArrayOutputStream binData = new ByteArrayOutputStream(); int binDataStartPC = -1; while (index < code.length) { final byte opCode = code[index]; OpCode op = OpCode.code(opCode); if (!mask.get(index)) { if (binDataStartPC == -1) { binDataStartPC = index; } binData.write(code[index]); index++; if (index < code.length) continue; } if (binDataStartPC != -1) { sb.append(formatBinData(binData.toByteArray(), binDataStartPC)); binDataStartPC = -1; binData = new ByteArrayOutputStream(); if (index == code.length) continue; } sb.append(Utils.align("" + Integer.toHexString(index) + ":", ' ', 8, false)); if (op == null) { sb.append("<UNKNOWN>: ").append(0xFF & opCode).append("\n"); index++; continue; } if (op.name().startsWith("PUSH")) { sb.append(' ').append(op.name()).append(' '); int nPush = op.val() - OpCode.PUSH1.val() + 1; byte[] data = Arrays.copyOfRange(code, index + 1, index + nPush + 1); BigInteger bi = new BigInteger(1, data); sb.append("0x").append(bi.toString(16)); if (bi.bitLength() <= 32) { sb.append(" (").append(new BigInteger(1, data).toString()).append(") "); } index += nPush + 1; } else { sb.append(' ').append(op.name()); index++; } sb.append('\n'); } return sb.toString(); } static class ByteCodeIterator { byte[] code; int pc; public ByteCodeIterator(byte[] code) { this.code = code; } public void setPC(int pc) { this.pc = pc; } public int getPC() { return pc; } public OpCode getCurOpcode() { return pc < code.length ? OpCode.code(code[pc]) : null; } public boolean isPush() { return getCurOpcode() != null ? getCurOpcode().name().startsWith("PUSH") : false; } public byte[] getCurOpcodeArg() { if (isPush()) { int nPush = getCurOpcode().val() - OpCode.PUSH1.val() + 1; byte[] data = Arrays.copyOfRange(code, pc + 1, pc + nPush + 1); return data; } else { return new byte[0]; } } public boolean next() { pc += 1 + getCurOpcodeArg().length; return pc < code.length; } } static BitSet buildReachableBytecodesMask(byte[] code) { NavigableSet<Integer> gotos = new TreeSet<>(); ByteCodeIterator it = new ByteCodeIterator(code); BitSet ret = new BitSet(code.length); int lastPush = 0; int lastPushPC = 0; do { ret.set(it.getPC()); // reachable bytecode if (it.isPush()) { lastPush = new BigInteger(1, it.getCurOpcodeArg()).intValue(); lastPushPC = it.getPC(); } if (it.getCurOpcode() == OpCode.JUMP || it.getCurOpcode() == OpCode.JUMPI) { if (it.getPC() != lastPushPC + 1) { // some PC arithmetic we totally can't deal with // assuming all bytecodes are reachable as a fallback ret.set(0, code.length); return ret; } int jumpPC = lastPush; if (!ret.get(jumpPC)) { // code was not explored yet gotos.add(jumpPC); } } if (it.getCurOpcode() == OpCode.JUMP || it.getCurOpcode() == OpCode.RETURN || it.getCurOpcode() == OpCode.STOP) { if (gotos.isEmpty()) break; it.setPC(gotos.pollFirst()); } } while (it.next()); return ret; } public static String stringify(byte[] code) { int index = 0; StringBuilder sb = new StringBuilder(); BitSet mask = buildReachableBytecodesMask(code); String binData = ""; while (index < code.length) { final byte opCode = code[index]; OpCode op = OpCode.code(opCode); if (op == null) { sb.append(" <UNKNOWN>: ").append(0xFF & opCode).append(" "); index++; continue; } if (op.name().startsWith("PUSH")) { sb.append(' ').append(op.name()).append(' '); int nPush = op.val() - OpCode.PUSH1.val() + 1; byte[] data = Arrays.copyOfRange(code, index + 1, index + nPush + 1); BigInteger bi = new BigInteger(1, data); sb.append("0x").append(bi.toString(16)).append(" "); index += nPush + 1; } else { sb.append(' ').append(op.name()); index++; } } return sb.toString(); } public void addListener(ProgramOutListener listener) { this.listener = listener; } public int verifyJumpDest(DataWord nextPC) { if (nextPC.bytesOccupied() > 4) { throw Program.Exception.badJumpDestination(-1); } int ret = nextPC.intValue(); if (!getProgramPrecompile().hasJumpDest(ret)) { throw Program.Exception.badJumpDestination(ret); } return ret; } public void callToPrecompiledAddress(MessageCall msg, PrecompiledContract contract) { returnDataBuffer = null; // reset return buffer right before the call if (getCallDeep() == MAX_DEPTH) { stackPushZero(); this.refundGas(msg.getGas().longValue(), " call deep limit reach"); return; } Repository track = getStorage().startTracking(); byte[] senderAddress = this.getOwnerAddress().getLast20Bytes(); byte[] codeAddress = msg.getCodeAddress().getLast20Bytes(); byte[] contextAddress = msg.getType().callIsStateless() ? senderAddress : codeAddress; BigInteger endowment = msg.getEndowment().value(); BigInteger senderBalance = track.getBalance(senderAddress); if (senderBalance.compareTo(endowment) < 0) { stackPushZero(); this.refundGas(msg.getGas().longValue(), "refund gas from message call"); return; } byte[] data = this.memoryChunk(msg.getInDataOffs().intValue(), msg.getInDataSize().intValue()); // Charge for endowment - is not reversible by rollback transfer(track, senderAddress, contextAddress, msg.getEndowment().value()); if (byTestingSuite()) { // This keeps track of the calls created for a test this.getResult().addCallCreate(data, msg.getCodeAddress().getLast20Bytes(), msg.getGas().getNoLeadZeroesData(), msg.getEndowment().getNoLeadZeroesData()); stackPushOne(); return; } long requiredGas = contract.getGasForData(data); if (requiredGas > msg.getGas().longValue()) { this.refundGas(0, "call pre-compiled"); //matches cpp logic this.stackPushZero(); track.rollback(); } else { if (logger.isDebugEnabled()) logger.debug("Call {}(data = {})", contract.getClass().getSimpleName(), toHexString(data)); Pair<Boolean, byte[]> out = contract.execute(data); if (out.getLeft()) { // success this.refundGas(msg.getGas().longValue() - requiredGas, "call pre-compiled"); this.stackPushOne(); returnDataBuffer = out.getRight(); track.commit(); } else { // spend all gas on failure, push zero and revert state changes this.refundGas(0, "call pre-compiled"); this.stackPushZero(); track.rollback(); } this.memorySave(msg.getOutDataOffs().intValue(), msg.getOutDataSize().intValueSafe(), out.getRight()); } } public boolean byTestingSuite() { return invoke.byTestingSuite(); } public interface ProgramOutListener { void output(String out); } /** * Denotes problem when executing Ethereum bytecode. * From blockchain and peer perspective this is quite normal situation * and doesn't mean exceptional situation in terms of the program execution */ @SuppressWarnings("serial") public static class BytecodeExecutionException extends RuntimeException { public BytecodeExecutionException(String message) { super(message); } } @SuppressWarnings("serial") public static class OutOfGasException extends BytecodeExecutionException { public OutOfGasException(String message, Object... args) { super(format(message, args)); } } @SuppressWarnings("serial") public static class IllegalOperationException extends BytecodeExecutionException { public IllegalOperationException(String message, Object... args) { super(format(message, args)); } } @SuppressWarnings("serial") public static class BadJumpDestinationException extends BytecodeExecutionException { public BadJumpDestinationException(String message, Object... args) { super(format(message, args)); } } @SuppressWarnings("serial") public static class StackTooSmallException extends BytecodeExecutionException { public StackTooSmallException(String message, Object... args) { super(format(message, args)); } } @SuppressWarnings("serial") public static class ReturnDataCopyIllegalBoundsException extends BytecodeExecutionException { public ReturnDataCopyIllegalBoundsException(DataWord off, DataWord size, long returnDataSize) { super(String.format("Illegal RETURNDATACOPY arguments: offset (%s) + size (%s) > RETURNDATASIZE (%d)", off, size, returnDataSize)); } } @SuppressWarnings("serial") public static class StaticCallModificationException extends BytecodeExecutionException { public StaticCallModificationException() { super("Attempt to call a state modifying opcode inside STATICCALL"); } } public static class Exception { public static OutOfGasException notEnoughOpGas(OpCode op, long opGas, long programGas) { return new OutOfGasException("Not enough gas for '%s' operation executing: opGas[%d], programGas[%d];", op, opGas, programGas); } public static OutOfGasException notEnoughOpGas(OpCode op, DataWord opGas, DataWord programGas) { return notEnoughOpGas(op, opGas.longValue(), programGas.longValue()); } public static OutOfGasException notEnoughOpGas(OpCode op, BigInteger opGas, BigInteger programGas) { return notEnoughOpGas(op, opGas.longValue(), programGas.longValue()); } public static OutOfGasException notEnoughSpendingGas(String cause, long gasValue, Program program) { return new OutOfGasException("Not enough gas for '%s' cause spending: invokeGas[%d], gas[%d], usedGas[%d];", cause, program.invoke.getGas().longValue(), gasValue, program.getResult().getGasUsed()); } public static OutOfGasException gasOverflow(BigInteger actualGas, BigInteger gasLimit) { return new OutOfGasException("Gas value overflow: actualGas[%d], gasLimit[%d];", actualGas.longValue(), gasLimit.longValue()); } public static IllegalOperationException invalidOpCode(byte... opCode) { return new IllegalOperationException("Invalid operation code: opCode[%s];", Hex.toHexString(opCode, 0, 1)); } public static BadJumpDestinationException badJumpDestination(int pc) { return new BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", pc); } public static StackTooSmallException tooSmallStack(int expectedSize, int actualSize) { return new StackTooSmallException("Expected stack size %d but actual %d;", expectedSize, actualSize); } } @SuppressWarnings("serial") public class StackTooLargeException extends BytecodeExecutionException { public StackTooLargeException(String message) { super(message); } } /** * used mostly for testing reasons */ public byte[] getMemory() { return memory.read(0, memory.size()); } /** * used mostly for testing reasons */ public void initMem(byte[] data) { this.memory.write(0, data, data.length, false); } }
52,276
35.480809
156
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/Stack.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.listener.ProgramListener; import org.ethereum.vm.program.listener.ProgramListenerAware; public class Stack extends java.util.Stack<DataWord> implements ProgramListenerAware { private ProgramListener programListener; @Override public void setProgramListener(ProgramListener listener) { this.programListener = listener; } @Override public synchronized DataWord pop() { if (programListener != null) programListener.onStackPop(); return super.pop(); } @Override public DataWord push(DataWord item) { if (programListener != null) programListener.onStackPush(item); return super.push(item); } public void swap(int from, int to) { if (isAccessible(from) && isAccessible(to) && (from != to)) { if (programListener != null) programListener.onStackSwap(from, to); DataWord tmp = get(from); set(from, set(to, tmp)); } } private boolean isAccessible(int from) { return from >= 0 && from < size(); } }
1,940
33.052632
86
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/Memory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.listener.ProgramListener; import org.ethereum.vm.program.listener.ProgramListenerAware; import java.util.LinkedList; import java.util.List; import static java.lang.Math.ceil; import static java.lang.Math.min; import static java.lang.String.format; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; import static org.ethereum.util.ByteUtil.oneByteToHexString; public class Memory implements ProgramListenerAware { private static final int CHUNK_SIZE = 1024; private static final int WORD_SIZE = 32; private List<byte[]> chunks = new LinkedList<>(); private int softSize; private ProgramListener programListener; @Override public void setProgramListener(ProgramListener traceListener) { this.programListener = traceListener; } public byte[] read(int address, int size) { if (size <= 0) return EMPTY_BYTE_ARRAY; extend(address, size); byte[] data = new byte[size]; int chunkIndex = address / CHUNK_SIZE; int chunkOffset = address % CHUNK_SIZE; int toGrab = data.length; int start = 0; while (toGrab > 0) { int copied = grabMax(chunkIndex, chunkOffset, toGrab, data, start); // read next chunk from the start ++chunkIndex; chunkOffset = 0; // mark remind toGrab -= copied; start += copied; } return data; } public void write(int address, byte[] data, int dataSize, boolean limited) { if (dataSize <= 0) return; if (data.length < dataSize) dataSize = data.length; if (!limited) extend(address, dataSize); int chunkIndex = address / CHUNK_SIZE; int chunkOffset = address % CHUNK_SIZE; int toCapture = 0; if (limited) toCapture = (address + dataSize > softSize) ? softSize - address : dataSize; else toCapture = dataSize; int start = 0; while (toCapture > 0) { int captured = captureMax(chunkIndex, chunkOffset, toCapture, data, start); // capture next chunk ++chunkIndex; chunkOffset = 0; // mark remind toCapture -= captured; start += captured; } if (programListener != null) programListener.onMemoryWrite(address, data, dataSize); } public void extendAndWrite(int address, int allocSize, byte[] data) { extend(address, allocSize); write(address, data, allocSize, false); } public void extend(int address, int size) { if (size <= 0) return; final int newSize = address + size; int toAllocate = newSize - internalSize(); if (toAllocate > 0) { addChunks((int) ceil((double) toAllocate / CHUNK_SIZE)); } toAllocate = newSize - softSize; if (toAllocate > 0) { toAllocate = (int) ceil((double) toAllocate / WORD_SIZE) * WORD_SIZE; softSize += toAllocate; if (programListener != null) programListener.onMemoryExtend(toAllocate); } } public DataWord readWord(int address) { return DataWord.of(read(address, 32)); } // just access expecting all data valid public byte readByte(int address) { int chunkIndex = address / CHUNK_SIZE; int chunkOffset = address % CHUNK_SIZE; byte[] chunk = chunks.get(chunkIndex); return chunk[chunkOffset]; } @Override public String toString() { StringBuilder memoryData = new StringBuilder(); StringBuilder firstLine = new StringBuilder(); StringBuilder secondLine = new StringBuilder(); for (int i = 0; i < softSize; ++i) { byte value = readByte(i); // Check if value is ASCII String character = ((byte) 0x20 <= value && value <= (byte) 0x7e) ? new String(new byte[]{value}) : "?"; firstLine.append(character).append(""); secondLine.append(oneByteToHexString(value)).append(" "); if ((i + 1) % 8 == 0) { String tmp = format("%4s", Integer.toString(i - 7, 16)).replace(" ", "0"); memoryData.append("").append(tmp).append(" "); memoryData.append(firstLine).append(" "); memoryData.append(secondLine); if (i + 1 < softSize) memoryData.append("\n"); firstLine.setLength(0); secondLine.setLength(0); } } return memoryData.toString(); } public int size() { return softSize; } public int internalSize() { return chunks.size() * CHUNK_SIZE; } public List<byte[]> getChunks() { return new LinkedList<>(chunks); } private int captureMax(int chunkIndex, int chunkOffset, int size, byte[] src, int srcPos) { byte[] chunk = chunks.get(chunkIndex); int toCapture = min(size, chunk.length - chunkOffset); System.arraycopy(src, srcPos, chunk, chunkOffset, toCapture); return toCapture; } private int grabMax(int chunkIndex, int chunkOffset, int size, byte[] dest, int destPos) { byte[] chunk = chunks.get(chunkIndex); int toGrab = min(size, chunk.length - chunkOffset); System.arraycopy(chunk, chunkOffset, dest, destPos, toGrab); return toGrab; } private void addChunks(int num) { for (int i = 0; i < num; ++i) { chunks.add(new byte[CHUNK_SIZE]); } } }
6,479
29.139535
116
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/InternalTransaction.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program; import java.math.BigInteger; import java.nio.ByteBuffer; import org.ethereum.core.Transaction; import org.ethereum.crypto.ECKey; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.ethereum.vm.DataWord; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.apache.commons.lang3.ArrayUtils.*; import static org.ethereum.util.ByteUtil.toHexString; public class InternalTransaction extends Transaction { private byte[] parentHash; private int deep; private int index; private boolean rejected = false; private String note; public InternalTransaction(byte[] rawData) { super(rawData); } public InternalTransaction(byte[] parentHash, int deep, int index, byte[] nonce, DataWord gasPrice, DataWord gasLimit, byte[] sendAddress, byte[] receiveAddress, byte[] value, byte[] data, String note) { super(nonce, getData(gasPrice), getData(gasLimit), receiveAddress, nullToEmpty(value), nullToEmpty(data)); this.parentHash = parentHash; this.deep = deep; this.index = index; this.sendAddress = nullToEmpty(sendAddress); this.note = note; this.parsed = true; } private static byte[] getData(DataWord gasPrice) { return (gasPrice == null) ? ByteUtil.EMPTY_BYTE_ARRAY : gasPrice.getData(); } public void reject() { this.rejected = true; } public int getDeep() { rlpParse(); return deep; } public int getIndex() { rlpParse(); return index; } public boolean isRejected() { rlpParse(); return rejected; } public String getNote() { rlpParse(); return note; } @Override public byte[] getSender() { rlpParse(); return sendAddress; } public byte[] getParentHash() { rlpParse(); return parentHash; } @Override public byte[] getEncoded() { if (rlpEncoded == null) { byte[] nonce = getNonce(); boolean isEmptyNonce = isEmpty(nonce) || (getLength(nonce) == 1 && nonce[0] == 0); this.rlpEncoded = RLP.encodeList( RLP.encodeElement(isEmptyNonce ? null : nonce), RLP.encodeElement(this.parentHash), RLP.encodeElement(getSender()), RLP.encodeElement(getReceiveAddress()), RLP.encodeElement(getValue()), RLP.encodeElement(getGasPrice()), RLP.encodeElement(getGasLimit()), RLP.encodeElement(getData()), RLP.encodeString(this.note), encodeInt(this.deep), encodeInt(this.index), encodeInt(this.rejected ? 1 : 0) ); } return rlpEncoded; } @Override public byte[] getEncodedRaw() { return getEncoded(); } @Override public synchronized void rlpParse() { if (parsed) return; RLPList decodedTxList = RLP.decode2(rlpEncoded); RLPList transaction = (RLPList) decodedTxList.get(0); setNonce(transaction.get(0).getRLPData()); this.parentHash = transaction.get(1).getRLPData(); this.sendAddress = transaction.get(2).getRLPData(); setReceiveAddress(transaction.get(3).getRLPData()); setValue(transaction.get(4).getRLPData()); setGasPrice(transaction.get(5).getRLPData()); setGasLimit(transaction.get(6).getRLPData()); setData(transaction.get(7).getRLPData()); this.note = new String(transaction.get(8).getRLPData()); this.deep = decodeInt(transaction.get(9).getRLPData()); this.index = decodeInt(transaction.get(10).getRLPData()); this.rejected = decodeInt(transaction.get(11).getRLPData()) == 1; this.parsed = true; } private static byte[] intToBytes(int value) { return ByteBuffer.allocate(Integer.SIZE / Byte.SIZE) .order(ByteOrder.LITTLE_ENDIAN) .putInt(value) .array(); } private static int bytesToInt(byte[] bytes) { return isEmpty(bytes) ? 0 : ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(); } private static byte[] encodeInt(int value) { return RLP.encodeElement(intToBytes(value)); } private static int decodeInt(byte[] encoded) { return bytesToInt(encoded); } @Override public ECKey getKey() { throw new UnsupportedOperationException("Cannot sign internal transaction."); } @Override public void sign(byte[] privKeyBytes) throws ECKey.MissingPrivateKeyException { throw new UnsupportedOperationException("Cannot sign internal transaction."); } @Override public String toString() { return "TransactionData [" + " parentHash=" + toHexString(getParentHash()) + ", hash=" + toHexString(getHash()) + ", nonce=" + toHexString(getNonce()) + ", gasPrice=" + toHexString(getGasPrice()) + ", gas=" + toHexString(getGasLimit()) + ", sendAddress=" + toHexString(getSender()) + ", receiveAddress=" + toHexString(getReceiveAddress()) + ", value=" + toHexString(getValue()) + ", data=" + toHexString(getData()) + ", note=" + getNote() + ", deep=" + getDeep() + ", index=" + getIndex() + ", rejected=" + isRejected() + "]"; } }
6,519
31.118227
122
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/invoke/ProgramInvoke.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.invoke; import org.ethereum.core.Repository; import org.ethereum.db.BlockStore; import org.ethereum.vm.DataWord; /** * @author Roman Mandeleil * @since 03.06.2014 */ public interface ProgramInvoke { DataWord getOwnerAddress(); DataWord getBalance(); DataWord getOriginAddress(); DataWord getCallerAddress(); DataWord getMinGasPrice(); DataWord getGas(); long getGasLong(); DataWord getCallValue(); DataWord getDataSize(); DataWord getDataValue(DataWord indexData); byte[] getDataCopy(DataWord offsetData, DataWord lengthData); DataWord getPrevHash(); DataWord getCoinbase(); DataWord getTimestamp(); DataWord getNumber(); DataWord getDifficulty(); DataWord getGaslimit(); boolean byTransaction(); boolean byTestingSuite(); int getCallDeep(); Repository getRepository(); Repository getOrigRepository(); BlockStore getBlockStore(); boolean isStaticCall(); }
1,803
22.128205
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/invoke/ProgramInvokeMockImpl.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.invoke; import org.ethereum.core.Repository; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.RepositoryRoot; import org.ethereum.db.BlockStore; import org.ethereum.db.BlockStoreDummy; import org.ethereum.vm.DataWord; import org.spongycastle.util.encoders.Hex; /** * @author Roman Mandeleil * @since 03.06.2014 */ public class ProgramInvokeMockImpl implements ProgramInvoke { private byte[] msgData; private Repository repository; private Repository origRepository; private byte[] ownerAddress = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"); private final byte[] contractAddress = Hex.decode("471fd3ad3e9eeadeec4608b92d16ce6b500704cc"); // default for most tests. This can be overwritten by the test private long gasLimit = 1000000; public ProgramInvokeMockImpl(byte[] msgDataRaw) { this(); this.msgData = msgDataRaw; } public ProgramInvokeMockImpl() { this.repository = new RepositoryRoot(new HashMapDB<byte[]>()); this.repository.createAccount(ownerAddress); this.repository.createAccount(contractAddress); this.repository.saveCode(contractAddress, Hex.decode("385E60076000396000605f556014600054601e60" + "205463abcddcba6040545b51602001600a525451" + "6040016014525451606001601e52545160800160" + "28525460a052546016604860003960166000f260" + "00603f556103e75660005460005360200235")); this.origRepository = this.repository.clone(); } public ProgramInvokeMockImpl(boolean defaults) { } /* ADDRESS op */ public DataWord getOwnerAddress() { return DataWord.of(ownerAddress); } /* BALANCE op */ public DataWord getBalance() { byte[] balance = Hex.decode("0DE0B6B3A7640000"); return DataWord.of(balance); } /* ORIGIN op */ public DataWord getOriginAddress() { byte[] cowPrivKey = HashUtil.sha3("horse".getBytes()); byte[] addr = ECKey.fromPrivate(cowPrivKey).getAddress(); return DataWord.of(addr); } /* CALLER op */ public DataWord getCallerAddress() { byte[] cowPrivKey = HashUtil.sha3("monkey".getBytes()); byte[] addr = ECKey.fromPrivate(cowPrivKey).getAddress(); return DataWord.of(addr); } /* GASPRICE op */ public DataWord getMinGasPrice() { byte[] minGasPrice = Hex.decode("09184e72a000"); return DataWord.of(minGasPrice); } /* GAS op */ public DataWord getGas() { return DataWord.of(gasLimit); } @Override public long getGasLong() { return gasLimit; } public void setGas(long gasLimit) { this.gasLimit = gasLimit; } /* CALLVALUE op */ public DataWord getCallValue() { byte[] balance = Hex.decode("0DE0B6B3A7640000"); return DataWord.of(balance); } /*****************/ /*** msg data ***/ /** * ************* */ /* CALLDATALOAD op */ public DataWord getDataValue(DataWord indexData) { byte[] data = new byte[32]; int index = indexData.value().intValue(); int size = 32; if (msgData == null) return DataWord.of(data); if (index > msgData.length) return DataWord.of(data); if (index + 32 > msgData.length) size = msgData.length - index; System.arraycopy(msgData, index, data, 0, size); return DataWord.of(data); } /* CALLDATASIZE */ public DataWord getDataSize() { if (msgData == null || msgData.length == 0) return DataWord.of(new byte[32]); int size = msgData.length; return DataWord.of(size); } /* CALLDATACOPY */ public byte[] getDataCopy(DataWord offsetData, DataWord lengthData) { int offset = offsetData.value().intValue(); int length = lengthData.value().intValue(); byte[] data = new byte[length]; if (msgData == null) return data; if (offset > msgData.length) return data; if (offset + length > msgData.length) length = msgData.length - offset; System.arraycopy(msgData, offset, data, 0, length); return data; } @Override public DataWord getPrevHash() { byte[] prevHash = Hex.decode("961CB117ABA86D1E596854015A1483323F18883C2D745B0BC03E87F146D2BB1C"); return DataWord.of(prevHash); } @Override public DataWord getCoinbase() { byte[] coinBase = Hex.decode("E559DE5527492BCB42EC68D07DF0742A98EC3F1E"); return DataWord.of(coinBase); } @Override public DataWord getTimestamp() { long timestamp = 1401421348; return DataWord.of(timestamp); } @Override public DataWord getNumber() { long number = 33; return DataWord.of(number); } @Override public DataWord getDifficulty() { byte[] difficulty = Hex.decode("3ED290"); return DataWord.of(difficulty); } @Override public DataWord getGaslimit() { return DataWord.of(gasLimit); } public void setGasLimit(long gasLimit) { this.gasLimit = gasLimit; } public void setOwnerAddress(byte[] ownerAddress) { this.ownerAddress = ownerAddress; } @Override public boolean byTransaction() { return true; } @Override public boolean isStaticCall() { return false; } @Override public boolean byTestingSuite() { return false; } @Override public Repository getRepository() { return this.repository; } @Override public Repository getOrigRepository() { return this.origRepository; } @Override public BlockStore getBlockStore() { return new BlockStoreDummy(); } public void setRepository(Repository repository) { this.repository = repository; } public void setOrigRepository(Repository repository) { this.origRepository = repository.clone(); } @Override public int getCallDeep() { return 0; } }
7,164
26.140152
105
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/invoke/ProgramInvokeImpl.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.invoke; import org.ethereum.core.Repository; import org.ethereum.db.BlockStore; import org.ethereum.vm.DataWord; import java.math.BigInteger; import java.util.Arrays; import java.util.Map; /** * @author Roman Mandeleil * @since 03.06.2014 */ public class ProgramInvokeImpl implements ProgramInvoke { private BlockStore blockStore; /** * TRANSACTION env ** */ private final DataWord address; private final DataWord origin, caller, balance, gas, gasPrice, callValue; private final long gasLong; byte[] msgData; /** * BLOCK env ** */ private final DataWord prevHash, coinbase, timestamp, number, difficulty, gaslimit; private Map<DataWord, DataWord> storage; private final Repository repository; private final Repository origRepository; private boolean byTransaction = true; private boolean byTestingSuite = false; private int callDeep = 0; private boolean isStaticCall = false; public ProgramInvokeImpl(DataWord address, DataWord origin, DataWord caller, DataWord balance, DataWord gasPrice, DataWord gas, DataWord callValue, byte[] msgData, DataWord lastHash, DataWord coinbase, DataWord timestamp, DataWord number, DataWord difficulty, DataWord gaslimit, Repository repository, Repository origRepository, int callDeep, BlockStore blockStore, boolean isStaticCall, boolean byTestingSuite) { // Transaction env this.address = address; this.origin = origin; this.caller = caller; this.balance = balance; this.gasPrice = gasPrice; this.gas = gas; this.gasLong = this.gas.longValueSafe(); this.callValue = callValue; this.msgData = msgData; // last Block env this.prevHash = lastHash; this.coinbase = coinbase; this.timestamp = timestamp; this.number = number; this.difficulty = difficulty; this.gaslimit = gaslimit; this.repository = repository; this.origRepository = origRepository; this.byTransaction = false; this.callDeep = callDeep; this.blockStore = blockStore; this.isStaticCall = isStaticCall; this.byTestingSuite = byTestingSuite; } public ProgramInvokeImpl(byte[] address, byte[] origin, byte[] caller, byte[] balance, byte[] gasPrice, byte[] gas, byte[] callValue, byte[] msgData, byte[] lastHash, byte[] coinbase, long timestamp, long number, byte[] difficulty, byte[] gaslimit, Repository repository, Repository origRepository, BlockStore blockStore, boolean byTestingSuite) { this(address, origin, caller, balance, gasPrice, gas, callValue, msgData, lastHash, coinbase, timestamp, number, difficulty, gaslimit, repository, origRepository, blockStore); this.byTestingSuite = byTestingSuite; } public ProgramInvokeImpl(byte[] address, byte[] origin, byte[] caller, byte[] balance, byte[] gasPrice, byte[] gas, byte[] callValue, byte[] msgData, byte[] lastHash, byte[] coinbase, long timestamp, long number, byte[] difficulty, byte[] gaslimit, Repository repository, Repository origRepository, BlockStore blockStore) { // Transaction env this.address = DataWord.of(address); this.origin = DataWord.of(origin); this.caller = DataWord.of(caller); this.balance = DataWord.of(balance); this.gasPrice = DataWord.of(gasPrice); this.gas = DataWord.of(gas); this.gasLong = this.gas.longValueSafe(); this.callValue = DataWord.of(callValue); this.msgData = msgData; // last Block env this.prevHash = DataWord.of(lastHash); this.coinbase = DataWord.of(coinbase); this.timestamp = DataWord.of(timestamp); this.number = DataWord.of(number); this.difficulty = DataWord.of(difficulty); this.gaslimit = DataWord.of(gaslimit); this.repository = repository; this.origRepository = origRepository; this.blockStore = blockStore; } /* ADDRESS op */ public DataWord getOwnerAddress() { return address; } /* BALANCE op */ public DataWord getBalance() { return balance; } /* ORIGIN op */ public DataWord getOriginAddress() { return origin; } /* CALLER op */ public DataWord getCallerAddress() { return caller; } /* GASPRICE op */ public DataWord getMinGasPrice() { return gasPrice; } /* GAS op */ public DataWord getGas() { return gas; } @Override public long getGasLong() { return gasLong; } /* CALLVALUE op */ public DataWord getCallValue() { return callValue; } /*****************/ /*** msg data ***/ /*****************/ /* NOTE: In the protocol there is no restriction on the maximum message data, * However msgData here is a byte[] and this can't hold more than 2^32-1 */ private static BigInteger MAX_MSG_DATA = BigInteger.valueOf(Integer.MAX_VALUE); /* CALLDATALOAD op */ public DataWord getDataValue(DataWord indexData) { BigInteger tempIndex = indexData.value(); int index = tempIndex.intValue(); // possible overflow is caught below int size = 32; // maximum datavalue size if (msgData == null || index >= msgData.length || tempIndex.compareTo(MAX_MSG_DATA) == 1) return DataWord.ZERO; if (index + size > msgData.length) size = msgData.length - index; byte[] data = new byte[32]; System.arraycopy(msgData, index, data, 0, size); return DataWord.of(data); } /* CALLDATASIZE */ public DataWord getDataSize() { if (msgData == null || msgData.length == 0) return DataWord.ZERO; int size = msgData.length; return DataWord.of(size); } /* CALLDATACOPY */ public byte[] getDataCopy(DataWord offsetData, DataWord lengthData) { int offset = offsetData.intValueSafe(); int length = lengthData.intValueSafe(); byte[] data = new byte[length]; if (msgData == null) return data; if (offset > msgData.length) return data; if (offset + length > msgData.length) length = msgData.length - offset; System.arraycopy(msgData, offset, data, 0, length); return data; } /* PREVHASH op */ public DataWord getPrevHash() { return prevHash; } /* COINBASE op */ public DataWord getCoinbase() { return coinbase; } /* TIMESTAMP op */ public DataWord getTimestamp() { return timestamp; } /* NUMBER op */ public DataWord getNumber() { return number; } /* DIFFICULTY op */ public DataWord getDifficulty() { return difficulty; } /* GASLIMIT op */ public DataWord getGaslimit() { return gaslimit; } /* Storage */ public Map<DataWord, DataWord> getStorage() { return storage; } public Repository getRepository() { return repository; } /** * Repository at the start of top-level ttransaction execution */ public Repository getOrigRepository() { return origRepository; } @Override public BlockStore getBlockStore() { return blockStore; } @Override public boolean byTransaction() { return byTransaction; } @Override public boolean isStaticCall() { return isStaticCall; } @Override public boolean byTestingSuite() { return byTestingSuite; } @Override public int getCallDeep() { return this.callDeep; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProgramInvokeImpl that = (ProgramInvokeImpl) o; if (byTestingSuite != that.byTestingSuite) return false; if (byTransaction != that.byTransaction) return false; if (address != null ? !address.equals(that.address) : that.address != null) return false; if (balance != null ? !balance.equals(that.balance) : that.balance != null) return false; if (callValue != null ? !callValue.equals(that.callValue) : that.callValue != null) return false; if (caller != null ? !caller.equals(that.caller) : that.caller != null) return false; if (coinbase != null ? !coinbase.equals(that.coinbase) : that.coinbase != null) return false; if (difficulty != null ? !difficulty.equals(that.difficulty) : that.difficulty != null) return false; if (gas != null ? !gas.equals(that.gas) : that.gas != null) return false; if (gasPrice != null ? !gasPrice.equals(that.gasPrice) : that.gasPrice != null) return false; if (gaslimit != null ? !gaslimit.equals(that.gaslimit) : that.gaslimit != null) return false; if (!Arrays.equals(msgData, that.msgData)) return false; if (number != null ? !number.equals(that.number) : that.number != null) return false; if (origin != null ? !origin.equals(that.origin) : that.origin != null) return false; if (prevHash != null ? !prevHash.equals(that.prevHash) : that.prevHash != null) return false; if (repository != null ? !repository.equals(that.repository) : that.repository != null) return false; if (origRepository != null ? !origRepository.equals(that.origRepository) : that.origRepository != null) return false; if (storage != null ? !storage.equals(that.storage) : that.storage != null) return false; if (timestamp != null ? !timestamp.equals(that.timestamp) : that.timestamp != null) return false; return true; } @Override public String toString() { return "ProgramInvokeImpl{" + "address=" + address + ", origin=" + origin + ", caller=" + caller + ", balance=" + balance + ", gas=" + gas + ", gasPrice=" + gasPrice + ", callValue=" + callValue + ", msgData=" + Arrays.toString(msgData) + ", prevHash=" + prevHash + ", coinbase=" + coinbase + ", timestamp=" + timestamp + ", number=" + number + ", difficulty=" + difficulty + ", gaslimit=" + gaslimit + ", storage=" + storage + ", repository=" + repository + ", origRepository=" + origRepository + ", byTransaction=" + byTransaction + ", byTestingSuite=" + byTestingSuite + ", callDeep=" + callDeep + '}'; } }
12,195
33.258427
125
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/invoke/ProgramInvokeFactoryImpl.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.invoke; import org.ethereum.core.Block; import org.ethereum.core.Blockchain; import org.ethereum.core.Repository; import org.ethereum.core.Transaction; import org.ethereum.db.BlockStore; import org.ethereum.util.ByteUtil; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.Program; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigInteger; import static org.apache.commons.lang3.ArrayUtils.nullToEmpty; /** * @author Roman Mandeleil * @since 08.06.2014 */ @Component("ProgramInvokeFactory") public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { private static final Logger logger = LoggerFactory.getLogger("VM"); // Invocation by the wire tx @Override public ProgramInvoke createProgramInvoke(Transaction tx, Block block, Repository repository, Repository origRepository, BlockStore blockStore) { /*** ADDRESS op ***/ // YP: Get address of currently executing account. byte[] address = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress(); /*** ORIGIN op ***/ // YP: This is the sender of original transaction; it is never a contract. byte[] origin = tx.getSender(); /*** CALLER op ***/ // YP: This is the address of the account that is directly responsible for this execution. byte[] caller = tx.getSender(); /*** BALANCE op ***/ byte[] balance = repository.getBalance(address).toByteArray(); /*** GASPRICE op ***/ byte[] gasPrice = tx.getGasPrice(); /*** GAS op ***/ byte[] gas = tx.getGasLimit(); /*** CALLVALUE op ***/ byte[] callValue = nullToEmpty(tx.getValue()); /*** CALLDATALOAD op ***/ /*** CALLDATACOPY op ***/ /*** CALLDATASIZE op ***/ byte[] data = tx.isContractCreation() ? ByteUtil.EMPTY_BYTE_ARRAY : nullToEmpty(tx.getData()); /*** PREVHASH op ***/ byte[] lastHash = block.getParentHash(); /*** COINBASE op ***/ byte[] coinbase = block.getCoinbase(); /*** TIMESTAMP op ***/ long timestamp = block.getTimestamp(); /*** NUMBER op ***/ long number = block.getNumber(); /*** DIFFICULTY op ***/ byte[] difficulty = block.getDifficulty(); /*** GASLIMIT op ***/ byte[] gaslimit = block.getGasLimit(); if (logger.isInfoEnabled()) { logger.info("Top level call: \n" + "tx.hash={}\n" + "address={}\n" + "origin={}\n" + "caller={}\n" + "balance={}\n" + "gasPrice={}\n" + "gas={}\n" + "callValue={}\n" + "data={}\n" + "lastHash={}\n" + "coinbase={}\n" + "timestamp={}\n" + "blockNumber={}\n" + "difficulty={}\n" + "gaslimit={}\n", ByteUtil.toHexString(tx.getHash()), ByteUtil.toHexString(address), ByteUtil.toHexString(origin), ByteUtil.toHexString(caller), ByteUtil.bytesToBigInteger(balance), ByteUtil.bytesToBigInteger(gasPrice), ByteUtil.bytesToBigInteger(gas), ByteUtil.bytesToBigInteger(callValue), ByteUtil.toHexString(data), ByteUtil.toHexString(lastHash), ByteUtil.toHexString(coinbase), timestamp, number, ByteUtil.toHexString(difficulty), gaslimit); } return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, timestamp, number, difficulty, gaslimit, repository, origRepository, blockStore); } /** * This invocation created for contract call contract */ @Override public ProgramInvoke createProgramInvoke(Program program, DataWord toAddress, DataWord callerAddress, DataWord inValue, DataWord inGas, BigInteger balanceInt, byte[] dataIn, Repository repository, Repository origRepository, BlockStore blockStore, boolean isStaticCall, boolean byTestingSuite) { DataWord address = toAddress; DataWord origin = program.getOriginAddress(); DataWord caller = callerAddress; DataWord balance = DataWord.of(balanceInt.toByteArray()); DataWord gasPrice = program.getGasPrice(); DataWord gas = inGas; DataWord callValue = inValue; byte[] data = dataIn; DataWord lastHash = program.getPrevHash(); DataWord coinbase = program.getCoinbase(); DataWord timestamp = program.getTimestamp(); DataWord number = program.getNumber(); DataWord difficulty = program.getDifficulty(); DataWord gasLimit = program.getGasLimit(); if (logger.isInfoEnabled()) { logger.info("Internal call: \n" + "address={}\n" + "origin={}\n" + "caller={}\n" + "balance={}\n" + "gasPrice={}\n" + "gas={}\n" + "callValue={}\n" + "data={}\n" + "lastHash={}\n" + "coinbase={}\n" + "timestamp={}\n" + "blockNumber={}\n" + "difficulty={}\n" + "gaslimit={}\n", ByteUtil.toHexString(address.getLast20Bytes()), ByteUtil.toHexString(origin.getLast20Bytes()), ByteUtil.toHexString(caller.getLast20Bytes()), balance.toString(), gasPrice.longValue(), gas.longValue(), ByteUtil.toHexString(callValue.getNoLeadZeroesData()), ByteUtil.toHexString(data), ByteUtil.toHexString(lastHash.getData()), ByteUtil.toHexString(coinbase.getLast20Bytes()), timestamp.longValue(), number.longValue(), ByteUtil.toHexString(difficulty.getNoLeadZeroesData()), gasLimit.bigIntValue()); } return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, timestamp, number, difficulty, gasLimit, repository, origRepository, program.getCallDeep() + 1, blockStore, isStaticCall, byTestingSuite); } }
8,280
39.99505
117
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/invoke/ProgramInvokeFactory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.invoke; import org.ethereum.core.Block; import org.ethereum.core.Repository; import org.ethereum.core.Transaction; import org.ethereum.db.BlockStore; import org.ethereum.vm.DataWord; import org.ethereum.vm.program.Program; import java.math.BigInteger; /** * @author Roman Mandeleil * @since 19.12.2014 */ public interface ProgramInvokeFactory { ProgramInvoke createProgramInvoke(Transaction tx, Block block, Repository repository, Repository origRepository, BlockStore blockStore); ProgramInvoke createProgramInvoke(Program program, DataWord toAddress, DataWord callerAddress, DataWord inValue, DataWord inGas, BigInteger balanceInt, byte[] dataIn, Repository repository, Repository origRepository, BlockStore blockStore, boolean staticCall, boolean byTestingSuite); }
1,826
38.717391
117
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/listener/ProgramStorageChangeListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.listener; import org.ethereum.vm.DataWord; import java.util.HashMap; import java.util.Map; public class ProgramStorageChangeListener extends ProgramListenerAdaptor { private Map<DataWord, DataWord> diff = new HashMap<>(); @Override public void onStoragePut(DataWord key, DataWord value) { diff.put(key, value); } @Override public void onStorageClear() { // TODO: ... } public Map<DataWord, DataWord> getDiff() { return new HashMap<>(diff); } public void merge(Map<DataWord, DataWord> diff) { this.diff.putAll(diff); } }
1,426
29.361702
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/listener/ProgramListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.listener; import org.ethereum.vm.DataWord; public interface ProgramListener { void onMemoryExtend(int delta); void onMemoryWrite(int address, byte[] data, int size); void onStackPop(); void onStackPush(DataWord value); void onStackSwap(int from, int to); void onStoragePut(DataWord key, DataWord value); void onStorageClear(); }
1,187
31.108108
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/listener/ProgramListenerAdaptor.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.listener; import org.ethereum.vm.DataWord; public class ProgramListenerAdaptor implements ProgramListener { @Override public void onMemoryExtend(int delta) { } @Override public void onMemoryWrite(int address, byte[] data, int size) { } @Override public void onStackPop() { } @Override public void onStackPush(DataWord value) { } @Override public void onStackSwap(int from, int to) { } @Override public void onStoragePut(DataWord key, DataWord value) { } @Override public void onStorageClear() { } }
1,421
23.101695
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/listener/ProgramListenerAware.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.listener; public interface ProgramListenerAware { void setProgramListener(ProgramListener listener); }
935
38
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/vm/program/listener/CompositeProgramListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.vm.program.listener; import org.ethereum.vm.DataWord; import java.util.ArrayList; import java.util.List; public class CompositeProgramListener implements ProgramListener { private List<ProgramListener> listeners = new ArrayList<>(); @Override public void onMemoryExtend(int delta) { for (ProgramListener listener : listeners) { listener.onMemoryExtend(delta); } } @Override public void onMemoryWrite(int address, byte[] data, int size) { for (ProgramListener listener : listeners) { listener.onMemoryWrite(address, data, size); } } @Override public void onStackPop() { for (ProgramListener listener : listeners) { listener.onStackPop(); } } @Override public void onStackPush(DataWord value) { for (ProgramListener listener : listeners) { listener.onStackPush(value); } } @Override public void onStackSwap(int from, int to) { for (ProgramListener listener : listeners) { listener.onStackSwap(from, to); } } @Override public void onStoragePut(DataWord key, DataWord value) { for (ProgramListener listener : listeners) { listener.onStoragePut(key, value); } } @Override public void onStorageClear() { for (ProgramListener listener : listeners) { listener.onStorageClear(); } } public void addListener(ProgramListener listener) { listeners.add(listener); } public boolean isEmpty() { return listeners.isEmpty(); } }
2,453
27.206897
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/PrivateMinerSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import com.typesafe.config.ConfigFactory; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.Transaction; import org.ethereum.crypto.ECKey; import org.ethereum.facade.EthereumFactory; import org.ethereum.mine.EthashListener; import org.ethereum.util.ByteUtil; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; /** * The sample creates a small private net with two peers: one is the miner, another is a regular peer * which is directly connected to the miner peer and starts submitting transactions which are then * included to blocks by the miner. * * Another concept demonstrated by this sample is the ability to run two independently configured * EthereumJ peers in a single JVM. For this two Spring ApplicationContext's are created which * are mostly differed by the configuration supplied * * Created by Anton Nashatyrev on 05.02.2016. */ public class PrivateMinerSample { /** * Spring configuration class for the Miner peer */ private static class MinerConfig { private final String config = // no need for discovery in that small network "peer.discovery.enabled = false \n" + "peer.listen.port = 30335 \n" + // need to have different nodeId's for the peers "peer.privateKey = 6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec \n" + // our private net ID "peer.networkId = 555 \n" + // we have no peers to sync with "sync.enabled = false \n" + // genesis with a lower initial difficulty and some predefined known funded accounts "genesis = sample-genesis.json \n" + // two peers need to have separate database dirs "database.dir = sampleDB-1 \n" + // when more than 1 miner exist on the network extraData helps to identify the block creator "mine.extraDataHex = cccccccccccccccccccc \n" + "mine.cpuMineThreads = 2 \n" + "cache.flush.blocks = 1"; @Bean public MinerNode node() { return new MinerNode(); } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } /** * Miner bean, which just start a miner upon creation and prints miner events */ static class MinerNode extends BasicSample implements EthashListener { public MinerNode() { // peers need different loggers super("sampleMiner"); } // overriding run() method since we don't need to wait for any discovery, // networking or sync events @Override public void run() { ethereum.getBlockMiner().addListener(this); ethereum.getBlockMiner().startMining(); } @Override public void onDatasetUpdate(EthashListener.DatasetStatus minerStatus) { logger.info("Miner status updated: {}", minerStatus); if (minerStatus.equals(EthashListener.DatasetStatus.FULL_DATASET_GENERATE_START)) { logger.info("Generating Full Dataset (may take up to 10 min if not cached)..."); } if (minerStatus.equals(DatasetStatus.FULL_DATASET_GENERATED)) { logger.info("Full dataset generated."); } } @Override public void miningStarted() { logger.info("Miner started"); } @Override public void miningStopped() { logger.info("Miner stopped"); } @Override public void blockMiningStarted(Block block) { logger.info("Start mining block: " + block.getShortDescr()); } @Override public void blockMined(Block block) { logger.info("Block mined! : \n" + block); } @Override public void blockMiningCanceled(Block block) { logger.info("Cancel mining block: " + block.getShortDescr()); } } /** * Spring configuration class for the Regular peer */ private static class RegularConfig { private final String config = // no discovery: we are connecting directly to the miner peer "peer.discovery.enabled = false \n" + "peer.listen.port = 30336 \n" + "peer.privateKey = 3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c \n" + "peer.networkId = 555 \n" + // actively connecting to the miner "peer.active = [" + " { url = 'enode://26ba1aadaf59d7607ad7f437146927d79e80312f026cfa635c6b2ccf2c5d3521f5812ca2beb3b295b14f97110e6448c1c7ff68f14c5328d43a3c62b44143e9b1@localhost:30335' }" + "] \n" + "sync.enabled = true \n" + // all peers in the same network need to use the same genesis block "genesis = sample-genesis.json \n" + // two peers need to have separate database dirs "database.dir = sampleDB-2 \n"; @Bean public RegularNode node() { return new RegularNode(); } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } /** * The second node in the network which connects to the miner * waits for the sync and starts submitting transactions. * Those transactions should be included into mined blocks and the peer * should receive those blocks back */ static class RegularNode extends BasicSample { public RegularNode() { // peers need different loggers super("sampleNode"); } @Override public void onSyncDone() { new Thread(() -> { try { generateTransactions(); } catch (Exception e) { logger.error("Error generating tx: ", e); } }).start(); } /** * Generate one simple value transfer transaction each 7 seconds. * Thus blocks will include one, several and none transactions */ private void generateTransactions() throws Exception{ logger.info("Start generating transactions..."); // the sender which some coins from the genesis ECKey senderKey = ECKey.fromPrivate(Hex.decode("6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec")); byte[] receiverAddr = Hex.decode("5db10750e8caff27f906b41c71b3471057dd2004"); for (int i = ethereum.getRepository().getNonce(senderKey.getAddress()).intValue(), j = 0; j < 20000; i++, j++) { { Transaction tx = new Transaction(ByteUtil.intToBytesNoLeadZeroes(i), ByteUtil.longToBytesNoLeadZeroes(50_000_000_000L), ByteUtil.longToBytesNoLeadZeroes(0xfffff), receiverAddr, new byte[]{77}, new byte[0], ethereum.getChainIdForNextBlock()); tx.sign(senderKey); logger.info("<== Submitting tx: " + tx); ethereum.submitTransaction(tx); } Thread.sleep(7000); } } } /** * Creating two EthereumJ instances with different config classes */ public static void main(String[] args) throws Exception { if (Runtime.getRuntime().maxMemory() < (1250L << 20)) { MinerNode.sLogger.error("Not enough JVM heap (" + (Runtime.getRuntime().maxMemory() >> 20) + "Mb) to generate DAG for mining (DAG requires min 1G). For this sample it is recommended to set -Xmx2G JVM option"); return; } BasicSample.sLogger.info("Starting EthtereumJ miner instance!"); EthereumFactory.createEthereum(MinerConfig.class); BasicSample.sLogger.info("Starting EthtereumJ regular instance!"); EthereumFactory.createEthereum(RegularConfig.class); } }
9,730
39.210744
221
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/PendingStateSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.Block; import org.ethereum.core.PendingState; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.ECKey; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.util.ByteUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.math.BigInteger; import java.util.*; import static org.ethereum.util.ByteUtil.toHexString; /** * PendingState is the ability to track the changes made by transaction immediately and not wait for * the block containing that transaction. * * This sample connects to the test network (it has a lot of free Ethers) and starts periodically * transferring funds to a random address. The pending state is monitored and you may see that * while the actual receiver balance remains the same right after transaction sent the pending * state reflects balance change immediately. * * While new blocks are arrived the sample monitors which of our transactions are included ot those blocks. * After each 5 transactions the sample stops sending transactions and waits for all transactions * are cleared (included to blocks) so the actual and pending receiver balances become equal. * * Created by Anton Nashatyrev on 05.02.2016. */ public class PendingStateSample extends TestNetSample { // remember here what transactions have been sent // removing transaction from here on block arrival private Map<ByteArrayWrapper, Transaction> pendingTxs = Collections.synchronizedMap( new HashMap<ByteArrayWrapper, Transaction>()); @Autowired PendingState pendingState; // some random receiver private byte[] receiverAddress = new ECKey().getAddress(); @Override public void onSyncDone() { ethereum.addListener(new EthereumListenerAdapter() { // listening here when the PendingState is updated with new transactions @Override public void onPendingTransactionsReceived(List<Transaction> transactions) { for (Transaction tx : transactions) { PendingStateSample.this.onPendingTransactionReceived(tx); } } // when block arrives look for our included transactions @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { PendingStateSample.this.onBlock(block, receipts); } }); new Thread(() -> { try { sendTransactions(); } catch (Exception e) { logger.error("Error while sending transactions", e); } }, "PendingStateSampleThread").start(); } /** * Periodically send value transfer transactions and each 5 transactions * wait for all sent transactions to be included into blocks */ void sendTransactions() throws InterruptedException { // initial sender nonce needs to be retrieved from the repository // for further transactions we just do nonce++ BigInteger nonce = ethereum.getRepository().getNonce(senderAddress); int weisToSend = 100; int count = 0; while(true) { if (count < 5) { Transaction tx = new Transaction( ByteUtil.bigIntegerToBytes(nonce), ByteUtil.longToBytesNoLeadZeroes(ethereum.getGasPrice()), ByteUtil.longToBytesNoLeadZeroes(1_000_000), receiverAddress, ByteUtil.longToBytesNoLeadZeroes(weisToSend), new byte[0], ethereum.getChainIdForNextBlock()); tx.sign(ECKey.fromPrivate(receiverAddress)); logger.info("<=== Sending transaction: " + tx); ethereum.submitTransaction(tx); nonce = nonce.add(BigInteger.ONE); count++; } else { if (pendingTxs.size() > 0) { logger.info("Waiting for transaction clearing. " + pendingTxs.size() + " transactions remain."); } else { logger.info("All transactions are included to blocks!"); count = 0; } } Thread.sleep(7000); } } /** * The PendingState is updated with a new pending transactions. * Prints the current receiver balance (based on blocks) and the pending balance * which should immediately reflect receiver balance change */ void onPendingTransactionReceived(Transaction tx) { logger.info("onPendingTransactionReceived: " + tx); if (Arrays.equals(tx.getSender(), senderAddress)) { BigInteger receiverBalance = ethereum.getRepository().getBalance(receiverAddress); BigInteger receiverBalancePending = pendingState.getRepository().getBalance(receiverAddress); logger.info(" + New pending transaction 0x" + toHexString(tx.getHash()).substring(0, 8)); pendingTxs.put(new ByteArrayWrapper(tx.getHash()), tx); logger.info("Receiver pending/current balance: " + receiverBalancePending + " / " + receiverBalance + " (" + pendingTxs.size() + " pending txs)"); } } /** * For each block we are looking for our transactions and clearing them * The actual receiver balance is confirmed upon block arrival */ public void onBlock(Block block, List<TransactionReceipt> receipts) { int cleared = 0; for (Transaction tx : block.getTransactionsList()) { ByteArrayWrapper txHash = new ByteArrayWrapper(tx.getHash()); Transaction ptx = pendingTxs.get(txHash); if (ptx != null) { logger.info(" - Pending transaction cleared 0x" + toHexString(tx.getHash()).substring(0, 8) + " in block " + block.getShortDescr()); pendingTxs.remove(txHash); cleared++; } } BigInteger receiverBalance = ethereum.getRepository().getBalance(receiverAddress); BigInteger receiverBalancePending = pendingState.getRepository().getBalance(receiverAddress); logger.info("" + cleared + " transactions cleared in the block " + block.getShortDescr()); logger.info("Receiver pending/current balance: " + receiverBalancePending + " / " + receiverBalance + " (" + pendingTxs.size() + " pending txs)"); } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class Config extends TestNetConfig{ @Override @Bean public TestNetSample sampleBean() { return new PendingStateSample(); } } // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } }
8,027
41.031414
116
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/TransactionBomb.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.Block; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionReceipt; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.spongycastle.util.encoders.Hex; import java.util.Collections; import java.util.List; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes; import static org.ethereum.util.ByteUtil.toHexString; public class TransactionBomb extends EthereumListenerAdapter { Ethereum ethereum = null; boolean startedTxBomb = false; public TransactionBomb(Ethereum ethereum) { this.ethereum = ethereum; } public static void main(String[] args) { Ethereum ethereum = EthereumFactory.createEthereum(); ethereum.addListener(new TransactionBomb(ethereum)); } @Override public void onSyncDone(SyncState state) { // We will send transactions only // after we have the full chain syncs // - in order to prevent old nonce usage startedTxBomb = true; System.err.println(" ~~~ SYNC DONE ~~~ "); } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { if (startedTxBomb){ byte[] sender = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"); long nonce = ethereum.getRepository().getNonce(sender).longValue();; for (int i=0; i < 20; ++i){ sendTx(nonce); ++nonce; sleep(10); } } } private void sendTx(long nonce){ byte[] gasPrice = longToBytesNoLeadZeroes(1_000_000_000_000L); byte[] gasLimit = longToBytesNoLeadZeroes(21000); byte[] toAddress = Hex.decode("9f598824ffa7068c1f2543f04efb58b6993db933"); byte[] value = longToBytesNoLeadZeroes(10_000); Transaction tx = new Transaction(longToBytesNoLeadZeroes(nonce), gasPrice, gasLimit, toAddress, value, null, ethereum.getChainIdForNextBlock()); byte[] privKey = sha3("cow".getBytes()); tx.sign(privKey); ethereum.getChannelManager().sendTransaction(Collections.singletonList(tx), null); System.err.println("Sending tx: " + toHexString(tx.getHash())); } private void sleep(int millis){ try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();} } }
3,405
31.438095
90
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/PrivateNetworkDiscoverySample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import com.google.common.base.Joiner; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValue; import com.typesafe.config.ConfigValueFactory; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.ECKey; import org.ethereum.facade.EthereumFactory; import org.ethereum.net.rlpx.discover.NodeManager; import org.ethereum.net.rlpx.discover.table.NodeEntry; import org.ethereum.net.server.Channel; import org.ethereum.net.server.ChannelManager; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * Testing peers discovery. * * The sample creates a small private net with three peers: * - first is point for discovery; * - two other ones will connect to first. * * Peers run on same IP 127.0.0.1 and are different by ports. * * After some time all peers should find each other. We use `peer.discovery.ip.list` config * option to point to discovery peer. * * Created by Stan Reshetnyk on 06.10.2016. */ public class PrivateNetworkDiscoverySample { /** * Creating 3 instances with different config classes */ public static void main(String[] args) throws Exception { BasicSample.sLogger.info("Starting main node to which others will connect to"); EthereumFactory.createEthereum(Node0Config.class); BasicSample.sLogger.info("Starting regular instance 1!"); EthereumFactory.createEthereum(Node1Config.class); BasicSample.sLogger.info("Starting regular instance 2!"); EthereumFactory.createEthereum(Node2Config.class); } /** * Spring configuration class for the Regular peer */ private static class RegularConfig { private final String discoveryNode; private final int nodeIndex; public RegularConfig(int nodeIndex, String discoveryNode) { this.nodeIndex = nodeIndex; this.discoveryNode = discoveryNode; } @Bean public BasicSample node() { return new BasicSample("sampleNode-" + nodeIndex) { @Autowired ChannelManager channelManager; @Autowired NodeManager nodeManager; { new Thread(() -> { try { Thread.sleep(5000); while (true) { if (logger != null) { Thread.sleep(15000); if (channelManager != null) { final Collection<Channel> activePeers = channelManager.getActivePeers(); final ArrayList<String> ports = new ArrayList<>(); for (Channel channel: activePeers) { ports.add(channel.getInetSocketAddress().getHostName() + ":" + channel.getInetSocketAddress().getPort()); } final Collection<NodeEntry> nodes = nodeManager.getTable().getAllNodes(); final ArrayList<String> nodesString = new ArrayList<>(); for (NodeEntry node: nodes) { nodesString.add(node.getNode().getHost() + ":" + node.getNode().getPort() + "@" + node.getNode().getHexId().substring(0, 6) ); } logger.info("channelManager.getActivePeers() " + activePeers.size() + " " + Joiner.on(", ").join(ports)); logger.info("nodeManager.getTable().getAllNodes() " + nodesString.size() + " " + Joiner.on(", ").join(nodesString)); } else { logger.info("Channel manager is null"); } } else { System.err.println("Logger is null for " + nodeIndex); } } } catch (Exception e) { logger.error("Error checking peers count: ", e); } }).start(); } @Override public void onSyncDone() { logger.info("onSyncDone"); } }; } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { return new SystemProperties(getConfig(nodeIndex, discoveryNode)); } } public static class Node0Config extends RegularConfig { public Node0Config() { super(0, null); } @Bean public SystemProperties systemProperties() { return super.systemProperties(); } @Bean public BasicSample node() { return super.node(); } } private static class Node1Config extends RegularConfig { public Node1Config() { super(1, "127.0.0.1:20000"); } @Bean public SystemProperties systemProperties() { return super.systemProperties(); } @Bean public BasicSample node() { return super.node(); } } private static class Node2Config extends RegularConfig{ public Node2Config() { super(2, "127.0.0.1:20000"); } @Bean public SystemProperties systemProperties() { return super.systemProperties(); } @Bean public BasicSample node() { return super.node(); } } private static Config getConfig(int index, String discoveryNode) { return ConfigFactory.empty() .withValue("peer.discovery.enabled", value(true)) .withValue("peer.discovery.external.ip", value("127.0.0.1")) .withValue("peer.discovery.bind.ip", value("127.0.0.1")) .withValue("peer.discovery.persist", value("false")) .withValue("peer.listen.port", value(20000 + index)) .withValue("peer.privateKey", value(Hex.toHexString(ECKey.fromPrivate(("" + index).getBytes()).getPrivKeyBytes()))) .withValue("peer.networkId", value(555)) .withValue("sync.enabled", value(true)) .withValue("database.incompatibleDatabaseBehavior", value("RESET")) .withValue("genesis", value("sample-genesis.json")) .withValue("database.dir", value("sampleDB-" + index)) .withValue("peer.discovery.ip.list", value(discoveryNode != null ? Arrays.asList(discoveryNode) : Arrays.asList())); } private static ConfigValue value(Object value) { return ConfigValueFactory.fromAnyRef(value); } }
8,214
35.838565
170
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/TestNetSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import com.typesafe.config.ConfigFactory; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.ECKey; import org.ethereum.facade.EthereumFactory; import org.springframework.context.annotation.Bean; import static org.ethereum.crypto.HashUtil.sha3; /** * This class just extends the BasicSample with the config which connect the peer to the test network * This class can be used as a base for free transactions testing * (everyone may use that 'cow' sender which has pretty enough fake coins) * * Created by Anton Nashatyrev on 10.02.2016. */ public class TestNetSample extends BasicSample { /** * Use that sender key to sign transactions */ protected final byte[] senderPrivateKey = sha3("cow".getBytes()); // sender address is derived from the private key protected final byte[] senderAddress = ECKey.fromPrivate(senderPrivateKey).getAddress(); protected abstract static class TestNetConfig { private final String config = // Ropsten revive network configuration "peer.discovery.enabled = true \n" + "peer.listen.port = 30303 \n" + "peer.networkId = 3 \n" + // a number of public peers for this network (not all of then may be functioning) "peer.active = [" + " {url = 'enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303'}," + " {url = 'enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303'}" + "] \n" + "sync.enabled = true \n" + // special genesis for this test network "genesis = ropsten.json \n" + "blockchain.config.name = 'ropsten' \n" + "database.dir = testnetSampleDb \n" + "cache.flush.memory = 0"; public abstract TestNetSample sampleBean(); @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } @Override public void onSyncDone() throws Exception { super.onSyncDone(); } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class SampleConfig extends TestNetConfig { @Bean public TestNetSample sampleBean() { return new TestNetSample(); } } // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(SampleConfig.class); } }
3,775
40.494505
191
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/SendTransaction.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.*; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.util.ByteUtil; import org.ethereum.util.blockchain.EtherUtil; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * With this simple example you can send transaction from address to address in live public network * To make it work you just need to set sender's private key and receiver's address * * Created by Alexander Samtsov on 12.08.16. */ public class SendTransaction extends BasicSample { private Map<ByteArrayWrapper, TransactionReceipt> txWaiters = Collections.synchronizedMap(new HashMap<ByteArrayWrapper, TransactionReceipt>()); @Override public void onSyncDone() throws Exception { ethereum.addListener(new EthereumListenerAdapter() { // when block arrives look for our included transactions @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { SendTransaction.this.onBlock(block, receipts); } }); String toAddress = ""; logger.info("Sending transaction to net and waiting for inclusion"); sendTxAndWait(Hex.decode(toAddress), new byte[0]); logger.info("Transaction included!");} private void onBlock(Block block, List<TransactionReceipt> receipts) { for (TransactionReceipt receipt : receipts) { ByteArrayWrapper txHashW = new ByteArrayWrapper(receipt.getTransaction().getHash()); if (txWaiters.containsKey(txHashW)) { txWaiters.put(txHashW, receipt); synchronized (this) { notifyAll(); } } } } private TransactionReceipt sendTxAndWait(byte[] receiveAddress, byte[] data) throws InterruptedException { byte[] senderPrivateKey = HashUtil.sha3("cow".getBytes()); byte[] fromAddress = ECKey.fromPrivate(senderPrivateKey).getAddress(); BigInteger nonce = ethereum.getRepository().getNonce(fromAddress); Transaction tx = new Transaction( ByteUtil.bigIntegerToBytes(nonce), ByteUtil.longToBytesNoLeadZeroes(ethereum.getGasPrice()), ByteUtil.longToBytesNoLeadZeroes(200000), receiveAddress, ByteUtil.bigIntegerToBytes(EtherUtil.convert(1, EtherUtil.Unit.WEI)), // Use EtherUtil.convert for easy value unit conversion data, ethereum.getChainIdForNextBlock()); tx.sign(ECKey.fromPrivate(senderPrivateKey)); logger.info("<=== Sending transaction: " + tx); ethereum.submitTransaction(tx); return waitForTx(tx.getHash()); } private TransactionReceipt waitForTx(byte[] txHash) throws InterruptedException { ByteArrayWrapper txHashW = new ByteArrayWrapper(txHash); txWaiters.put(txHashW, null); long startBlock = ethereum.getBlockchain().getBestBlock().getNumber(); while(true) { TransactionReceipt receipt = txWaiters.get(txHashW); if (receipt != null) { return receipt; } else { long curBlock = ethereum.getBlockchain().getBestBlock().getNumber(); if (curBlock > startBlock + 16) { throw new RuntimeException("The transaction was not included during last 16 blocks: " + txHashW.toString().substring(0,8)); } else { logger.info("Waiting for block with transaction 0x" + txHashW.toString().substring(0,8) + " included (" + (curBlock - startBlock) + " blocks received so far) ..."); } } synchronized (this) { wait(20000); } } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class Config { @Bean public BasicSample sampleBean() { return new SendTransaction(); } } // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } }
5,445
37.083916
143
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/RopstenSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import com.typesafe.config.ConfigFactory; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.springframework.context.annotation.Bean; /** * This class just extends the BasicSample with the config which connect the peer to the Morden network * This class can be used as a base for free transactions testing * Everyone may use that 'cow' sender (which is effectively address aacc23ff079d96a5502b31fefcda87a6b3fbdcfb) * If you need more coins on this account just go to https://morden.ether.camp/ * and push 'Get Free Ether' button. * * Created by Anton Nashatyrev on 10.02.2016. */ public class RopstenSample extends BasicSample { /** * Use that sender key to sign transactions */ protected final byte[] senderPrivateKey = HashUtil.sha3("cow".getBytes()); // sender address is derived from the private key aacc23ff079d96a5502b31fefcda87a6b3fbdcfb protected final byte[] senderAddress = ECKey.fromPrivate(senderPrivateKey).getAddress(); protected abstract static class RopstenSampleConfig { private final String config = "peer.discovery = {" + " enabled = true \n" + " ip.list = [" + " '94.242.229.4:40404'," + " '94.242.229.203:30303'" + " ]" + "} \n" + "peer.p2p.eip8 = true \n" + "peer.networkId = 3 \n" + "sync.enabled = true \n" + "genesis = ropsten.json \n" + "blockchain.config.name = 'ropsten' \n" + "database.dir = database-ropstenSample"; public abstract RopstenSample sampleBean(); @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class SampleConfig extends RopstenSampleConfig { @Bean public RopstenSample sampleBean() { return new RopstenSample(); } } Ethereum ethereum = EthereumFactory.createEthereum(SampleConfig.class); } }
3,307
38.380952
109
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/EventListenerSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.Block; import org.ethereum.core.CallTransaction; import org.ethereum.core.PendingStateImpl; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.ECKey; import org.ethereum.db.BlockStore; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.db.TransactionStore; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.BlockReplay; import org.ethereum.listener.EthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.listener.EventListener; import org.ethereum.listener.TxStatus; import org.ethereum.solidity.compiler.CompilationResult; import org.ethereum.solidity.compiler.SolidityCompiler; import org.ethereum.util.ByteUtil; import org.ethereum.vm.program.ProgramResult; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.toHexString; /** * Sample usage of events listener API. * {@link EventListener} Contract events listener * {@link BlockReplay} Listener wrapper for pushing old blocks to any listener in addition to live data * * - getting free Ether assuming we are running in test network * - deploying contract with event, which we are going to track * - calling contract and catching corresponding events * - alternatively you could provide address of already deployed contract and * replay any number of blocks in the past to process old events */ public class EventListenerSample extends TestNetSample { @Autowired SolidityCompiler compiler; @Autowired BlockStore blockStore; @Autowired TransactionStore transactionStore; @Autowired PendingStateImpl pendingState; // Change seed phrases protected final byte[] senderPrivateKey = sha3("cat".getBytes()); protected final byte[] sender2PrivateKey = sha3("goat".getBytes()); // If no contractAddress provided, deploys new contract, otherwise // replays events from already deployed contract String contractAddress = null; // String contractAddress = "cedf27de170a05cf1d1736f21e1f5ffc1cf22eef"; String contract = "contract Sample {\n" + " int i;\n" + " event Inc(\n" + " address _from,\n" + " int _inc,\n" + " int _total\n" + " ); \n" + " \n" + " function inc(int n) {\n" + " i = i + n;\n" + " Inc(msg.sender, n, i); \n" + " } \n" + " \n" + " function get() returns (int) {\n" + " return i; \n" + " }\n" + "} "; private Map<ByteArrayWrapper, TransactionReceipt> txWaiters = Collections.synchronizedMap(new HashMap<ByteArrayWrapper, TransactionReceipt>()); class IncEvent { IncEvent(String address, Long inc, Long total) { this.address = address; this.inc = inc; this.total = total; } String address; Long inc; Long total; @Override public String toString() { return "IncEvent{" + "address='" + address + '\'' + ", inc=" + inc + ", total=" + total + '}'; } } class IncEventListener extends EventListener<IncEvent> { /** * Minimum required Tx block confirmations for the events * from this Tx to be confirmed * After this number of confirmations, event will fire {@link #processConfirmed(PendingEvent, IncEvent)} * on each confirmation */ protected int blocksToConfirm = 32; /** * Minimum required Tx block confirmations for this Tx to be purged * from the tracking list * After this number of confirmations, event will not fire {@link #processConfirmed(PendingEvent, IncEvent)} */ protected int purgeFromPendingsConfirmations = 40; public IncEventListener(PendingStateImpl pendingState) { super(pendingState); } public IncEventListener(PendingStateImpl pendingState, String contractABI, byte[] contractAddress) { super(pendingState); initContractAddress(contractABI, contractAddress); // Instead you can init with topic search, // so you could get events from all contracts with the same code // You could init listener only once // initContractTopic(contractABI, sha3("Inc(address,int256,int256)".getBytes())); } @Override protected IncEvent onEvent(CallTransaction.Invocation event, Block block, TransactionReceipt receipt, int txCount, EthereumListener.PendingTransactionState state) { // Processing raw event data to fill our model IncEvent if ("Inc".equals(event.function.name)) { String address = Hex.toHexString((byte[]) event.args[0]); Long inc = ((BigInteger) event.args[1]).longValue(); Long total = ((BigInteger) event.args[2]).longValue(); IncEvent incEvent = new IncEvent(address, inc, total); logger.info("Pending event: {}", incEvent); return incEvent; } else { logger.error("Unknown event: " + event); } return null; } @Override protected void pendingTransactionsUpdated() { } /** * Events are fired here on every block since blocksToConfirm to purgeFromPendingsConfirmations */ void processConfirmed(PendingEvent evt, IncEvent event) { // +1 because on included block we have 1 confirmation long numberOfConfirmations = evt.bestConfirmingBlock.getNumber() - evt.includedTo.getNumber() + 1; logger.info("Confirmed event: {}, confirmations: {}", event, numberOfConfirmations); } @Override protected boolean pendingTransactionUpdated(PendingEvent evt) { if (evt.txStatus == TxStatus.REJECTED || evt.txStatus.confirmed >= blocksToConfirm) { evt.eventData.forEach(d -> processConfirmed(evt, d)); } return evt.txStatus == TxStatus.REJECTED || evt.txStatus.confirmed >= purgeFromPendingsConfirmations; } } /** * Sample logic starts here when sync is done */ @Override public void onSyncDone() throws Exception { ethereum.addListener(new EthereumListenerAdapter() { @Override public void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block) { ByteArrayWrapper txHashW = new ByteArrayWrapper(txReceipt.getTransaction().getHash()); // Catching transaction errors if (txWaiters.containsKey(txHashW) && !txReceipt.isSuccessful()) { txWaiters.put(txHashW, txReceipt); } } }); requestFreeEther(ECKey.fromPrivate(senderPrivateKey).getAddress()); requestFreeEther(ECKey.fromPrivate(sender2PrivateKey).getAddress()); if (contractAddress == null) { deployContractAndTest(); } else { replayOnly(); } } public void requestFreeEther(byte[] addressBytes) { String address = "0x" + toHexString(addressBytes); logger.info("Checking address {} for available ether.", address); BigInteger balance = ethereum.getRepository().getBalance(addressBytes); logger.info("Address {} balance: {} wei", address, balance); BigInteger requiredBalance = BigInteger.valueOf(3_000_000 * ethereum.getGasPrice()); if (balance.compareTo(requiredBalance) < 0) { logger.info("Insufficient funds for address {}, requesting free ether", address); try { String result = postQuery("https://ropsten.faucet.b9lab.com/tap", "{\"toWhom\":\"" + address + "\"}"); logger.info("Answer from free Ether API: {}", result); waitForEther(addressBytes, requiredBalance); } catch (Exception ex) { logger.error("Error during request of free Ether,", ex); } } } private String postQuery(String endPoint, String json) throws IOException { URL url = new URL(endPoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(json.getBytes("UTF-8")); os.close(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); String result = null; try (Scanner scanner = new Scanner(in, "UTF-8")) { result = scanner.useDelimiter("\\A").next(); } in.close(); conn.disconnect(); return result; } private void waitForEther(byte[] address, BigInteger requiredBalance) throws InterruptedException { while(true) { BigInteger balance = ethereum.getRepository().getBalance(address); if (balance.compareTo(requiredBalance) > 0) { logger.info("Address {} successfully funded. Balance: {} wei", "0x" + toHexString(address), balance); break; } synchronized (this) { wait(20000); } } } /** * - Deploys contract * - Adds events listener * - Calls contract from 2 different addresses */ private void deployContractAndTest() throws Exception { ethereum.addListener(new EthereumListenerAdapter() { // when block arrives look for our included transactions @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { EventListenerSample.this.onBlock(block, receipts); } }); CompilationResult.ContractMetadata metadata = compileContract(); logger.info("Sending contract to net and waiting for inclusion"); TransactionReceipt receipt = sendTxAndWait(new byte[0], Hex.decode(metadata.bin), senderPrivateKey); if (!receipt.isSuccessful()) { logger.error("Some troubles creating a contract: " + receipt.getError()); return; } byte[] address = receipt.getTransaction().getContractAddress(); logger.info("Contract created: " + toHexString(address)); IncEventListener eventListener = new IncEventListener(pendingState, metadata.abi, address); ethereum.addListener(eventListener.listener); CallTransaction.Contract contract = new CallTransaction.Contract(metadata.abi); contractIncCall(senderPrivateKey, 777, metadata.abi, address); contractIncCall(sender2PrivateKey, 555, metadata.abi, address); ProgramResult r = ethereum.callConstantFunction(Hex.toHexString(address), contract.getByName("get")); Object[] ret = contract.getByName("get").decodeResult(r.getHReturn()); logger.info("Current contract data member value: " + ret[0]); } /** * Replays contract events for old blocks * using {@link BlockReplay} with {@link EventListener} */ private void replayOnly() throws Exception { logger.info("Contract already deployed to address 0x{}, using it", contractAddress); CompilationResult.ContractMetadata metadata = compileContract(); byte[] address = Hex.decode(contractAddress); IncEventListener eventListener = new IncEventListener(pendingState, metadata.abi, address); BlockReplay blockReplay = new BlockReplay(blockStore, transactionStore, eventListener.listener, blockStore.getMaxNumber() - 5000); ethereum.addListener(blockReplay); blockReplay.replayAsync(); } private CompilationResult.ContractMetadata compileContract() throws IOException { logger.info("Compiling contract..."); SolidityCompiler.Result result = compiler.compileSrc(contract.getBytes(), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN); if (result.isFailed()) { throw new RuntimeException("Contract compilation failed:\n" + result.errors); } CompilationResult res = CompilationResult.parse(result.output); if (res.getContracts().isEmpty()) { throw new RuntimeException("Compilation failed, no contracts returned:\n" + result.errors); } CompilationResult.ContractMetadata metadata = res.getContracts().iterator().next(); if (metadata.bin == null || metadata.bin.isEmpty()) { throw new RuntimeException("Compilation failed, no binary returned:\n" + result.errors); } return metadata; } private void contractIncCall(byte[] privateKey, int incAmount, String contractABI, byte[] contractAddress) throws InterruptedException { logger.info("Calling the contract function 'inc'"); CallTransaction.Contract contract = new CallTransaction.Contract(contractABI); CallTransaction.Function inc = contract.getByName("inc"); byte[] functionCallBytes = inc.encode(incAmount); TransactionReceipt receipt = sendTxAndWait(contractAddress, functionCallBytes, privateKey); if (!receipt.isSuccessful()) { logger.error("Some troubles invoking the contract: " + receipt.getError()); return; } logger.info("Contract modified!"); } protected TransactionReceipt sendTxAndWait(byte[] receiveAddress, byte[] data, byte[] privateKey) throws InterruptedException { BigInteger nonce = ethereum.getRepository().getNonce(ECKey.fromPrivate(privateKey).getAddress()); Transaction tx = new Transaction( ByteUtil.bigIntegerToBytes(nonce), ByteUtil.longToBytesNoLeadZeroes(ethereum.getGasPrice()), ByteUtil.longToBytesNoLeadZeroes(3_000_000), receiveAddress, ByteUtil.longToBytesNoLeadZeroes(0), data, ethereum.getChainIdForNextBlock()); tx.sign(ECKey.fromPrivate(privateKey)); logger.info("<=== Sending transaction: " + tx); ByteArrayWrapper txHashW = new ByteArrayWrapper(tx.getHash()); txWaiters.put(txHashW, null); ethereum.submitTransaction(tx); return waitForTx(txHashW); } private void onBlock(Block block, List<TransactionReceipt> receipts) { for (TransactionReceipt receipt : receipts) { ByteArrayWrapper txHashW = new ByteArrayWrapper(receipt.getTransaction().getHash()); if (txWaiters.containsKey(txHashW)) { txWaiters.put(txHashW, receipt); synchronized (this) { notifyAll(); } } } } protected TransactionReceipt waitForTx(ByteArrayWrapper txHashW) throws InterruptedException { long startBlock = ethereum.getBlockchain().getBestBlock().getNumber(); while(true) { TransactionReceipt receipt = txWaiters.get(txHashW); if (receipt != null) { return receipt; } else { long curBlock = ethereum.getBlockchain().getBestBlock().getNumber(); if (curBlock > startBlock + 16) { throw new RuntimeException("The transaction was not included during last 16 blocks: " + txHashW.toString().substring(0,8)); } else { logger.info("Waiting for block with transaction 0x" + txHashW.toString().substring(0,8) + " included (" + (curBlock - startBlock) + " blocks received so far) ..."); } } synchronized (this) { wait(20000); } } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class Config extends TestNetConfig{ @Override @Bean public TestNetSample sampleBean() { return new EventListenerSample(); } } // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } }
18,329
40.470588
172
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/MordenSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import com.typesafe.config.ConfigFactory; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.springframework.context.annotation.Bean; /** * This class just extends the BasicSample with the config which connect the peer to the Morden network * This class can be used as a base for free transactions testing * Everyone may use that 'cow' sender (which is effectively address aacc23ff079d96a5502b31fefcda87a6b3fbdcfb) * If you need more coins on this account just go to https://morden.ether.camp/ * and push 'Get Free Ether' button. * * Created by Anton Nashatyrev on 10.02.2016. */ public class MordenSample extends BasicSample { /** * Use that sender key to sign transactions */ protected final byte[] senderPrivateKey = HashUtil.sha3("cow".getBytes()); // sender address is derived from the private key aacc23ff079d96a5502b31fefcda87a6b3fbdcfb protected final byte[] senderAddress = ECKey.fromPrivate(senderPrivateKey).getAddress(); protected abstract static class MordenSampleConfig { private final String config = "peer.discovery = {" + " enabled = true \n" + " ip.list = [" + " '94.242.229.4:40404'," + " '94.242.229.203:30303'" + " ]" + "} \n" + "peer.p2p.eip8 = true \n" + "peer.networkId = 2 \n" + "sync.enabled = true \n" + "genesis = frontier-morden.json \n" + "blockchain.config.name = 'morden' \n" + "database.dir = mordenSampleDb"; public abstract MordenSample sampleBean(); @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class SampleConfig extends MordenSampleConfig { @Bean public MordenSample sampleBean() { return new MordenSample(); } } Ethereum ethereum = EthereumFactory.createEthereum(SampleConfig.class); } }
3,300
38.297619
109
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/PriceFeedSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.CallTransaction; import org.ethereum.facade.EthereumFactory; import org.ethereum.util.ByteUtil; import org.ethereum.util.Utils; import org.ethereum.vm.program.ProgramResult; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import java.math.BigInteger; import java.util.Date; /** * This sample demonstrates how constant calls works (that is transactions which are * not broadcasted to network, executed locally, don't change the blockchain state and can * report function return values). * Constant calls can actually invoke contract functions which are not formally 'const' * i.e. which change the contract storage state, but after such calls the contract * storage will remain unmodified. * * As a side effect this sample shows how Java wrappers for Ethereum contracts can be * created and then manipulated as regular Java objects * * Created by Anton Nashatyrev on 05.02.2016. */ public class PriceFeedSample extends BasicSample { /** * Base class for a Ethereum Contract wrapper * It can be used by two ways: * 1. for each function specify its name and input/output formal parameters * 2. Pass the contract JSON ABI to the constructor and then refer the function by name only */ abstract class EthereumContract { private final static String zeroAddr = "0000000000000000000000000000000000000000"; private final String contractAddr; private CallTransaction.Contract contractFromABI = null; /** * @param contractAddr address of the target contract as a hex String */ protected EthereumContract(String contractAddr) { this.contractAddr = contractAddr; } /** * Use this variant if you have the contract ABI then you call the functions * by their names only */ public EthereumContract(String contractAddr, String contractABI) { this.contractAddr = contractAddr; this.contractFromABI = new CallTransaction.Contract(contractABI); } /** * The main method of this demo which illustrates how to call a constant function. * To identify the Solidity contract function (calculate its signature) we need : * - function name * - a list of function formal params how they are declared in declaration * Output parameter types are required only for decoding the return values. * * Input arguments Java -> Solidity mapping is the following: * Number, BigInteger, String (hex) -> any integer type * byte[], String (hex) -> bytesN, byte[] * String -> string * Java array of the above types -> Solidity dynamic array of the corresponding type * * Output arguments Solidity -> Java mapping: * any integer type -> BigInteger * string -> String * bytesN, byte[] -> byte[] * Solidity dynamic array -> Java array */ protected Object[] callFunction(String name, String[] inParamTypes, String[] outParamTypes, Object ... args) { CallTransaction.Function function = CallTransaction.Function.fromSignature(name, inParamTypes, outParamTypes); ProgramResult result = ethereum.callConstantFunction(contractAddr, function, args); return function.decodeResult(result.getHReturn()); } /** * Use this method if the contract ABI was passed */ protected Object[] callFunction(String functionName, Object ... args) { if (contractFromABI == null) { throw new RuntimeException("The contract JSON ABI should be passed to constructor to use this method"); } CallTransaction.Function function = contractFromABI.getByName(functionName); ProgramResult result = ethereum.callConstantFunction(contractAddr, function, args); return function.decodeResult(result.getHReturn()); } /** * Checks if the contract exist in the repository */ public boolean isExist() { return !contractAddr.equals(zeroAddr) && ethereum.getRepository().isExist(Hex.decode(contractAddr)); } } /** * NameReg contract which manages a registry of contracts which can be accessed by name * * Here we resolve contract functions by specifying their name and input/output types * * Contract sources, live state and many more here: * https://live.ether.camp/account/985509582b2c38010bfaa3c8d2be60022d3d00da */ class NameRegContract extends EthereumContract { public NameRegContract() { super("985509582b2c38010bfaa3c8d2be60022d3d00da"); } public byte[] addressOf(String name) { BigInteger bi = (BigInteger) callFunction("addressOf", new String[] {"bytes32"}, new String[] {"address"}, name)[0]; return ByteUtil.bigIntegerToBytes(bi, 20); } public String nameOf(byte[] addr) { return (String) callFunction("nameOf", new String[]{"address"}, new String[]{"bytes32"}, addr)[0]; } } /** * PriceFeed contract where prices for several securities are stored and updated periodically * * This contract is created using its JSON ABI representation * * Contract sources, live state and many more here: * https://live.ether.camp/account/1194e966965418c7d73a42cceeb254d875860356 */ class PriceFeedContract extends EthereumContract { private static final String contractABI = "[{" + " 'constant': true," + " 'inputs': [{" + " 'name': 'symbol'," + " 'type': 'bytes32'" + " }]," + " 'name': 'getPrice'," + " 'outputs': [{" + " 'name': 'currPrice'," + " 'type': 'uint256'" + " }]," + " 'type': 'function'" + "}, {" + " 'constant': true," + " 'inputs': [{" + " 'name': 'symbol'," + " 'type': 'bytes32'" + " }]," + " 'name': 'getTimestamp'," + " 'outputs': [{" + " 'name': 'timestamp'," + " 'type': 'uint256'" + " }]," + " 'type': 'function'" + "}, {" + " 'constant': true," + " 'inputs': []," + " 'name': 'updateTime'," + " 'outputs': [{" + " 'name': ''," + " 'type': 'uint256'" + " }]," + " 'type': 'function'" + "}, {" + " 'inputs': []," + " 'type': 'constructor'" + "}]"; public PriceFeedContract(String contractAddr) { super(contractAddr, contractABI.replace("'", "\"")); //JSON parser doesn't like single quotes :( } public Date updateTime() { BigInteger ret = (BigInteger) callFunction("updateTime")[0]; // All times in Ethereum are Unix times return new Date(Utils.fromUnixTime(ret.longValue())); } public double getPrice(String ticker) { BigInteger ret = (BigInteger) callFunction("getPrice", ticker)[0]; // since Ethereum has no decimal numbers we are storing prices with // virtual fixed point return ret.longValue() / 1_000_000d; } public Date getTimestamp(String ticker) { BigInteger ret = (BigInteger) callFunction("getTimestamp", ticker)[0]; return new Date(Utils.fromUnixTime(ret.longValue())); } } @Override public void onSyncDone() { try { // after all blocks are synced perform the work // worker(); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected void waitForDiscovery() throws Exception { super.waitForDiscovery(); worker(); } /** * The method retrieves the information from the PriceFeed contract once in a minute and prints * the result in log. */ private void worker() throws Exception{ NameRegContract nameRegContract = new NameRegContract(); if (!nameRegContract.isExist()) { throw new RuntimeException("Namereg contract not exist on the blockchain"); } String priceFeedAddress = Hex.toHexString(nameRegContract.addressOf("ether-camp/price-feed")); logger.info("Got PriceFeed address from name registry: " + priceFeedAddress); PriceFeedContract priceFeedContract = new PriceFeedContract(priceFeedAddress); logger.info("Polling cryptocurrency exchange rates once a minute (prices are normally updated each 10 mins)..."); String[] tickers = {"BTC_ETH", "USDT_BTC", "USDT_ETH"}; while(true) { if (priceFeedContract.isExist()) { String s = priceFeedContract.updateTime() + ": "; for (String ticker : tickers) { s += ticker + " " + priceFeedContract.getPrice(ticker) + " (" + priceFeedContract.getTimestamp(ticker) + "), "; } logger.info(s); } else { logger.info("PriceFeed contract not exist. Likely it was not yet created until current block"); } Thread.sleep(60 * 1000); } } private static class Config { @Bean public PriceFeedSample priceFeedSample() { return new PriceFeedSample(); } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); // Based on Config class the sample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } }
11,040
38.859206
131
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/StandaloneBlockchainSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.util.blockchain.SolidityContract; import org.ethereum.util.blockchain.StandaloneBlockchain; import java.math.BigInteger; /** * The class demonstrates usage of the StandaloneBlockchain helper class * which greatly simplifies Solidity contract testing on a locally created * blockchain * * Created by Anton Nashatyrev on 04.04.2016. */ public class StandaloneBlockchainSample { // Pretty simple (and probably the most expensive) Calculator private static final String contractSrc = "contract Calculator {" + " int public result;" + // public field can be accessed by calling 'result' function " function add(int num) {" + " result = result + num;" + " }" + " function sub(int num) {" + " result = result - num;" + " }" + " function mul(int num) {" + " result = result * num;" + " }" + " function div(int num) {" + " result = result / num;" + " }" + " function clear() {" + " result = 0;" + " }" + "}"; public static void main(String[] args) throws Exception { // Creating a blockchain which generates a new block for each transaction // just not to call createBlock() after each call transaction StandaloneBlockchain bc = new StandaloneBlockchain().withAutoblock(true); System.out.println("Creating first empty block (need some time to generate DAG)..."); // warning up the block miner just to understand how long // the initial miner dataset is generated bc.createBlock(); System.out.println("Creating a contract..."); // This compiles our Solidity contract, submits it to the blockchain // internally generates the block with this transaction and returns the // contract interface SolidityContract calc = bc.submitNewContract(contractSrc); System.out.println("Calculating..."); // Creates the contract call transaction, submits it to the blockchain // and generates a new block which includes this transaction // After new block is generated the contract state is changed calc.callFunction("add", 100); // Check the contract state with a constant call which returns result // but doesn't generate any transactions and remain the contract state unchanged assertEqual(BigInteger.valueOf(100), (BigInteger) calc.callConstFunction("result")[0]); calc.callFunction("add", 200); assertEqual(BigInteger.valueOf(300), (BigInteger) calc.callConstFunction("result")[0]); calc.callFunction("mul", 10); assertEqual(BigInteger.valueOf(3000), (BigInteger) calc.callConstFunction("result")[0]); calc.callFunction("div", 5); assertEqual(BigInteger.valueOf(600), (BigInteger) calc.callConstFunction("result")[0]); System.out.println("Clearing..."); calc.callFunction("clear"); assertEqual(BigInteger.valueOf(0), (BigInteger) calc.callConstFunction("result")[0]); // We are done - the Solidity contract worked as expected. System.out.println("Done."); } private static void assertEqual(BigInteger n1, BigInteger n2) { if (!n1.equals(n2)) { throw new RuntimeException("Assertion failed: " + n1 + " != " + n2); } } }
4,291
44.659574
98
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/CreateContractSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.Block; import org.ethereum.core.CallTransaction; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.ECKey; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.solidity.compiler.CompilationResult; import org.ethereum.solidity.compiler.SolidityCompiler; import org.ethereum.util.ByteUtil; import org.ethereum.vm.program.ProgramResult; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.math.BigInteger; import java.util.*; import static org.ethereum.util.ByteUtil.toHexString; /** * Created by Anton Nashatyrev on 03.03.2016. */ public class CreateContractSample extends TestNetSample { @Autowired SolidityCompiler compiler; String contract = "contract Sample {" + " int i;" + " function inc(int n) {" + " i = i + n;" + " }" + " function get() returns (int) {" + " return i;" + " }" + "}"; private Map<ByteArrayWrapper, TransactionReceipt> txWaiters = Collections.synchronizedMap(new HashMap<ByteArrayWrapper, TransactionReceipt>()); @Override public void onSyncDone() throws Exception { ethereum.addListener(new EthereumListenerAdapter() { // when block arrives look for our included transactions @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { CreateContractSample.this.onBlock(block, receipts); } }); logger.info("Compiling contract..."); SolidityCompiler.Result result = compiler.compileSrc(contract.getBytes(), true, true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN); if (result.isFailed()) { throw new RuntimeException("Contract compilation failed:\n" + result.errors); } CompilationResult res = CompilationResult.parse(result.output); if (res.getContracts().isEmpty()) { throw new RuntimeException("Compilation failed, no contracts returned:\n" + result.errors); } CompilationResult.ContractMetadata metadata = res.getContracts().iterator().next(); if (metadata.bin == null || metadata.bin.isEmpty()) { throw new RuntimeException("Compilation failed, no binary returned:\n" + result.errors); } logger.info("Sending contract to net and waiting for inclusion"); TransactionReceipt receipt = sendTxAndWait(new byte[0], Hex.decode(metadata.bin)); if (!receipt.isSuccessful()) { logger.error("Some troubles creating a contract: " + receipt.getError()); return; } byte[] contractAddress = receipt.getTransaction().getContractAddress(); logger.info("Contract created: " + toHexString(contractAddress)); logger.info("Calling the contract function 'inc'"); CallTransaction.Contract contract = new CallTransaction.Contract(metadata.abi); CallTransaction.Function inc = contract.getByName("inc"); byte[] functionCallBytes = inc.encode(777); TransactionReceipt receipt1 = sendTxAndWait(contractAddress, functionCallBytes); if (!receipt1.isSuccessful()) { logger.error("Some troubles invoking the contract: " + receipt.getError()); return; } logger.info("Contract modified!"); ProgramResult r = ethereum.callConstantFunction(Hex.toHexString(contractAddress), contract.getByName("get")); Object[] ret = contract.getByName("get").decodeResult(r.getHReturn()); logger.info("Current contract data member value: " + ret[0]); } protected TransactionReceipt sendTxAndWait(byte[] receiveAddress, byte[] data) throws InterruptedException { BigInteger nonce = ethereum.getRepository().getNonce(senderAddress); Transaction tx = new Transaction( ByteUtil.bigIntegerToBytes(nonce), ByteUtil.longToBytesNoLeadZeroes(ethereum.getGasPrice()), ByteUtil.longToBytesNoLeadZeroes(3_000_000), receiveAddress, ByteUtil.longToBytesNoLeadZeroes(0), data, ethereum.getChainIdForNextBlock()); tx.sign(ECKey.fromPrivate(senderPrivateKey)); logger.info("<=== Sending transaction: " + tx); ethereum.submitTransaction(tx); return waitForTx(tx.getHash()); } private void onBlock(Block block, List<TransactionReceipt> receipts) { for (TransactionReceipt receipt : receipts) { ByteArrayWrapper txHashW = new ByteArrayWrapper(receipt.getTransaction().getHash()); if (txWaiters.containsKey(txHashW)) { txWaiters.put(txHashW, receipt); synchronized (this) { notifyAll(); } } } } protected TransactionReceipt waitForTx(byte[] txHash) throws InterruptedException { ByteArrayWrapper txHashW = new ByteArrayWrapper(txHash); txWaiters.put(txHashW, null); long startBlock = ethereum.getBlockchain().getBestBlock().getNumber(); while(true) { TransactionReceipt receipt = txWaiters.get(txHashW); if (receipt != null) { return receipt; } else { long curBlock = ethereum.getBlockchain().getBestBlock().getNumber(); if (curBlock > startBlock + 16) { throw new RuntimeException("The transaction was not included during last 16 blocks: " + txHashW.toString().substring(0,8)); } else { logger.info("Waiting for block with transaction 0x" + txHashW.toString().substring(0,8) + " included (" + (curBlock - startBlock) + " blocks received so far) ..."); } } synchronized (this) { wait(20000); } } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); class Config extends TestNetConfig{ @Override @Bean public TestNetSample sampleBean() { return new CreateContractSample(); } } // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } }
7,615
40.391304
143
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/BasicSample.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.message.StatusMessage; import org.ethereum.net.message.Message; import org.ethereum.net.p2p.HelloMessage; import org.ethereum.net.rlpx.Node; import org.ethereum.net.server.Channel; import org.ethereum.util.ByteUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import javax.annotation.PostConstruct; import java.util.*; /** * The base sample class which creates EthereumJ instance, tracks and report all the stages * of starting up like discovering nodes, connecting, syncing * * The class can be started as a standalone sample it should just run until full blockchain * sync and then just hanging, listening for new blocks and importing them into a DB * * This class is a Spring Component which makes it convenient to easily get access (autowire) to * all components created within EthereumJ. However almost all this could be done without dealing * with the Spring machinery from within a simple main method * * Created by Anton Nashatyrev on 05.02.2016. */ public class BasicSample implements Runnable { public static final Logger sLogger = LoggerFactory.getLogger("sample"); private static CustomFilter CUSTOM_FILTER; private String loggerName; protected Logger logger; @Autowired protected Ethereum ethereum; @Autowired protected SystemProperties config; private volatile long txCount; private volatile long gasSpent; // Spring config class which add this sample class as a bean to the components collections // and make it possible for autowiring other components private static class Config { @Bean public BasicSample basicSample() { return new BasicSample(); } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); // Based on Config class the BasicSample would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } public BasicSample() { this("sample"); } /** * logger name can be passed if more than one EthereumJ instance is created * in a single JVM to distinguish logging output from different instances */ public BasicSample(String loggerName) { this.loggerName = loggerName; } protected void setupLogging() { addSampleLogger(loggerName); logger = LoggerFactory.getLogger(loggerName); } /** * Allow only selected logger to print DEBUG events to STDOUT and FILE. * Other loggers are allowed to print ERRORS only. */ private static void addSampleLogger(final String loggerName) { if (CUSTOM_FILTER == null) { CUSTOM_FILTER = new CustomFilter(); final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Appender ca = loggerContext.getLogger("ROOT").getAppender("STDOUT"); ca.clearAllFilters(); ca.addFilter(CUSTOM_FILTER); } CUSTOM_FILTER.addVisibleLogger(loggerName); } /** * The method is called after all EthereumJ instances are created */ @PostConstruct private void springInit() { setupLogging(); // adding the main EthereumJ callback to be notified on different kind of events ethereum.addListener(listener); logger.info("Sample component created. Listening for ethereum events..."); // starting lifecycle tracking method run() new Thread(this, "SampleWorkThread").start(); } /** * The method tracks step-by-step the instance lifecycle from node discovery till sync completion. * At the end the method onSyncDone() is called which might be overridden by a sample subclass * to start making other things with the Ethereum network */ public void run() { try { logger.info("Sample worker thread started."); if (config.peerDiscovery()) { waitForDiscovery(); } else { logger.info("Peer discovery disabled. We should actively connect to another peers or wait for incoming connections"); } waitForAvailablePeers(); waitForSyncPeers(); waitForFirstBlock(); waitForSync(); onSyncDone(); } catch (Exception e) { logger.error("Error occurred in Sample: ", e); } } /** * Is called when the whole blockchain sync is complete */ public void onSyncDone() throws Exception { logger.info("Monitoring new blocks in real-time..."); } protected List<Node> nodesDiscovered = new Vector<>(); /** * Waits until any new nodes are discovered by the UDP discovery protocol */ protected void waitForDiscovery() throws Exception { logger.info("Waiting for nodes discovery..."); int bootNodes = config.peerDiscoveryIPList().size(); int cnt = 0; while(true) { Thread.sleep(cnt < 30 ? 300 : 5000); if (nodesDiscovered.size() > bootNodes) { logger.info("[v] Discovery works, new nodes started being discovered."); return; } if (cnt >= 30) logger.warn("Discovery keeps silence. Waiting more..."); if (cnt > 50) { logger.error("Looks like discovery failed, no nodes were found.\n" + "Please check your Firewall/NAT UDP protocol settings.\n" + "Your IP interface was detected as " + config.bindIp() + ", please check " + "if this interface is correct, otherwise set it manually via 'peer.discovery.bind.ip' option."); throw new RuntimeException("Discovery failed."); } cnt++; } } protected Map<Node, StatusMessage> ethNodes = new Hashtable<>(); /** * Discovering nodes is only the first step. No we need to find among discovered nodes * those ones which are live, accepting inbound connections, and has compatible subprotocol versions */ protected void waitForAvailablePeers() throws Exception { logger.info("Waiting for available Eth capable nodes..."); int cnt = 0; while(true) { Thread.sleep(cnt < 30 ? 1000 : 5000); if (ethNodes.size() > 0) { logger.info("[v] Available Eth nodes found."); return; } if (cnt >= 30) logger.info("No Eth nodes found so far. Keep searching..."); if (cnt > 60) { logger.error("No eth capable nodes found. Logs need to be investigated."); // throw new RuntimeException("Eth nodes failed."); } cnt++; } } protected List<Node> syncPeers = new Vector<>(); /** * When live nodes found SyncManager should select from them the most * suitable and add them as peers for syncing the blocks */ protected void waitForSyncPeers() throws Exception { logger.info("Searching for peers to sync with..."); int cnt = 0; while(true) { Thread.sleep(cnt < 30 ? 1000 : 5000); if (syncPeers.size() > 0) { logger.info("[v] At least one sync peer found."); return; } if (cnt >= 30) logger.info("No sync peers found so far. Keep searching..."); if (cnt > 60) { logger.error("No sync peers found. Logs need to be investigated."); // throw new RuntimeException("Sync peers failed."); } cnt++; } } protected Block bestBlock = null; /** * Waits until blocks import started */ protected void waitForFirstBlock() throws Exception { Block currentBest = ethereum.getBlockchain().getBestBlock(); logger.info("Current BEST block: " + currentBest.getShortDescr()); logger.info("Waiting for blocks start importing (may take a while)..."); int cnt = 0; while(true) { Thread.sleep(cnt < 300 ? 1000 : 60000); if (bestBlock != null && bestBlock.getNumber() > currentBest.getNumber()) { logger.info("[v] Blocks import started."); return; } if (cnt >= 300) logger.info("Still no blocks. Be patient..."); if (cnt > 330) { logger.error("No blocks imported during a long period. Must be a problem, logs need to be investigated."); // throw new RuntimeException("Block import failed."); } cnt++; } } boolean synced = false; boolean syncComplete = false; /** * Waits until the whole blockchain sync is complete */ private void waitForSync() throws Exception { logger.info("Waiting for the whole blockchain sync (will take up to several hours for the whole chain)..."); while(true) { Thread.sleep(10000); if (synced) { logger.info("[v] Sync complete! The best block: " + bestBlock.getShortDescr()); syncComplete = true; return; } logger.info("Blockchain sync in progress. Last imported block: " + bestBlock.getShortDescr() + " (Total: txs: " + txCount + ", gas: " + (gasSpent / 1000) + "k)"); txCount = 0; gasSpent = 0; } } /** * The main EthereumJ callback. */ EthereumListener listener = new EthereumListenerAdapter() { @Override public void onSyncDone(SyncState state) { synced = true; } @Override public void onNodeDiscovered(Node node) { if (nodesDiscovered.size() < 1000) { nodesDiscovered.add(node); } } @Override public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) { ethNodes.put(channel.getNode(), statusMessage); } @Override public void onPeerAddedToSyncPool(Channel peer) { syncPeers.add(peer.getNode()); } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { bestBlock = block; txCount += receipts.size(); for (TransactionReceipt receipt : receipts) { gasSpent += ByteUtil.byteArrayToLong(receipt.getGasUsed()); } if (syncComplete) { logger.info("New block: " + block.getShortDescr()); } } @Override public void onRecvMessage(Channel channel, Message message) { } @Override public void onSendMessage(Channel channel, Message message) { } @Override public void onPeerDisconnect(String host, long port) { } @Override public void onPendingTransactionsReceived(List<Transaction> transactions) { } @Override public void onPendingStateChanged(PendingState pendingState) { } @Override public void onHandShakePeer(Channel channel, HelloMessage helloMessage) { } @Override public void onNoConnections() { } @Override public void onVMTraceCreated(String transactionHash, String trace) { } @Override public void onTransactionExecuted(TransactionExecutionSummary summary) { } }; private static class CustomFilter extends Filter<ILoggingEvent> { private Set<String> visibleLoggers = new HashSet<>(); @Override public synchronized FilterReply decide(ILoggingEvent event) { return visibleLoggers.contains(event.getLoggerName()) && event.getLevel().isGreaterOrEqual(Level.INFO) || event.getLevel().isGreaterOrEqual(Level.ERROR) ? FilterReply.NEUTRAL : FilterReply.DENY; } public synchronized void addVisibleLogger(String name) { visibleLoggers.add(name); } } }
13,683
33.38191
133
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/FollowAccount.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.core.Block; import org.ethereum.core.TransactionReceipt; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.facade.Repository; import org.ethereum.listener.EthereumListenerAdapter; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.util.List; public class FollowAccount extends EthereumListenerAdapter { Ethereum ethereum = null; public FollowAccount(Ethereum ethereum) { this.ethereum = ethereum; } public static void main(String[] args) { Ethereum ethereum = EthereumFactory.createEthereum(); ethereum.addListener(new FollowAccount(ethereum)); } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { byte[] cow = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"); // Get snapshot some time ago - 10% blocks ago long bestNumber = ethereum.getBlockchain().getBestBlock().getNumber(); long oldNumber = (long) (bestNumber * 0.9); Block oldBlock = ethereum.getBlockchain().getBlockByNumber(oldNumber); Repository repository = ethereum.getRepository(); Repository snapshot = ethereum.getSnapshotTo(oldBlock.getStateRoot()); BigInteger nonce_ = snapshot.getNonce(cow); BigInteger nonce = repository.getNonce(cow); System.err.println(" #" + block.getNumber() + " [cd2a3d9] => snapshot_nonce:" + nonce_ + " latest_nonce:" + nonce); } }
2,335
34.393939
124
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/samples/CheckFork.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.samples; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.datasource.Source; import org.ethereum.db.IndexedBlockStore; import java.util.List; /** * Created by Anton Nashatyrev on 21.07.2016. */ public class CheckFork { public static void main(String[] args) throws Exception { SystemProperties.getDefault().overrideParams("database.dir", ""); Source<byte[], byte[]> index = CommonConfig.getDefault().cachedDbSource("index"); Source<byte[], byte[]> blockDS = CommonConfig.getDefault().cachedDbSource("block"); IndexedBlockStore indexedBlockStore = new IndexedBlockStore(); indexedBlockStore.init(index, blockDS); for (int i = 1_919_990; i < 1_921_000; i++) { Block chainBlock = indexedBlockStore.getChainBlockByNumber(i); List<Block> blocks = indexedBlockStore.getBlocksByNumber(i); String s = chainBlock.getShortDescr() + " ("; for (Block block : blocks) { if (!block.isEqual(chainBlock)) { s += block.getShortDescr() + " "; } } System.out.println(s); } } }
2,053
37.754717
91
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/BlockMiner.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.collections4.CollectionUtils; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.db.BlockStore; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.db.IndexedBlockStore; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumImpl; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.mine.MinerIfc.MiningResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigInteger; import java.util.*; import java.util.concurrent.*; import static java.lang.Math.max; /** * Manages embedded CPU mining and allows to use external miners. * * Created by Anton Nashatyrev on 10.12.2015. */ @Component public class BlockMiner { private static final Logger logger = LoggerFactory.getLogger("mine"); private static ExecutorService executor = Executors.newSingleThreadExecutor(); private Blockchain blockchain; private BlockStore blockStore; @Autowired private Ethereum ethereum; protected PendingState pendingState; private CompositeEthereumListener listener; private SystemProperties config; private List<MinerListener> listeners = new CopyOnWriteArrayList<>(); private BigInteger minGasPrice; private long minBlockTimeout; private int cpuThreads; private boolean fullMining = true; private volatile boolean isLocalMining; private Block miningBlock; private volatile MinerIfc externalMiner; private final Queue<ListenableFuture<MiningResult>> currentMiningTasks = new ConcurrentLinkedQueue<>(); private long lastBlockMinedTime; private int UNCLE_LIST_LIMIT; private int UNCLE_GENERATION_LIMIT; @Autowired public BlockMiner(final SystemProperties config, final CompositeEthereumListener listener, final Blockchain blockchain, final BlockStore blockStore, final PendingState pendingState) { this.listener = listener; this.config = config; this.blockchain = blockchain; this.blockStore = blockStore; this.pendingState = pendingState; UNCLE_LIST_LIMIT = config.getBlockchainConfig().getCommonConstants().getUNCLE_LIST_LIMIT(); UNCLE_GENERATION_LIMIT = config.getBlockchainConfig().getCommonConstants().getUNCLE_GENERATION_LIMIT(); minGasPrice = config.getMineMinGasPrice(); minBlockTimeout = config.getMineMinBlockTimeoutMsec(); cpuThreads = config.getMineCpuThreads(); fullMining = config.isMineFullDataset(); listener.addListener(new EthereumListenerAdapter() { @Override public void onPendingStateChanged(PendingState pendingState) { BlockMiner.this.onPendingStateChanged(); } @Override public void onSyncDone(SyncState state) { if (config.minerStart() && config.isSyncEnabled()) { logger.info("Sync complete, start mining..."); startMining(); } } }); if (config.minerStart() && !config.isSyncEnabled()) { logger.info("Sync disabled, start mining now..."); startMining(); } } public void setFullMining(boolean fullMining) { this.fullMining = fullMining; } public void setCpuThreads(int cpuThreads) { this.cpuThreads = cpuThreads; } public void setMinGasPrice(BigInteger minGasPrice) { this.minGasPrice = minGasPrice; } public void setExternalMiner(MinerIfc miner) { externalMiner = miner; restartMining(); } public void startMining() { isLocalMining = true; fireMinerStarted(); logger.info("Miner started"); restartMining(); } public void stopMining() { isLocalMining = false; cancelCurrentBlock(); fireMinerStopped(); logger.info("Miner stopped"); } protected List<Transaction> getAllPendingTransactions() { PendingStateImpl.TransactionSortedSet ret = new PendingStateImpl.TransactionSortedSet(); ret.addAll(pendingState.getPendingTransactions()); Iterator<Transaction> it = ret.iterator(); while(it.hasNext()) { Transaction tx = it.next(); if (!isAcceptableTx(tx)) { logger.debug("Miner excluded the transaction: {}", tx); it.remove(); } } return new ArrayList<>(ret); } private void onPendingStateChanged() { if (!isLocalMining && externalMiner == null) return; logger.debug("onPendingStateChanged()"); if (miningBlock == null) { restartMining(); } else if (miningBlock.getNumber() <= ((PendingStateImpl) pendingState).getBestBlock().getNumber()) { logger.debug("Restart mining: new best block: " + blockchain.getBestBlock().getShortDescr()); restartMining(); } else if (!CollectionUtils.isEqualCollection(miningBlock.getTransactionsList(), getAllPendingTransactions())) { logger.debug("Restart mining: pending transactions changed"); restartMining(); } else { if (logger.isDebugEnabled()) { String s = "onPendingStateChanged() event, but pending Txs the same as in currently mining block: "; for (Transaction tx : getAllPendingTransactions()) { s += "\n " + tx; } logger.debug(s); } } } protected boolean isAcceptableTx(Transaction tx) { return minGasPrice.compareTo(new BigInteger(1, tx.getGasPrice())) <= 0; } protected synchronized void cancelCurrentBlock() { for (ListenableFuture<MiningResult> task : currentMiningTasks) { if (task != null && !task.isCancelled()) { task.cancel(true); } } currentMiningTasks.clear(); if (miningBlock != null) { fireBlockCancelled(miningBlock); logger.debug("Tainted block mining cancelled: {}", miningBlock.getShortDescr()); miningBlock = null; } } protected List<BlockHeader> getUncles(Block mineBest) { List<BlockHeader> ret = new ArrayList<>(); long miningNum = mineBest.getNumber() + 1; Block mineChain = mineBest; long limitNum = max(0, miningNum - UNCLE_GENERATION_LIMIT); Set<ByteArrayWrapper> ancestors = BlockchainImpl.getAncestors(blockStore, mineBest, UNCLE_GENERATION_LIMIT + 1, true); Set<ByteArrayWrapper> knownUncles = ((BlockchainImpl)blockchain).getUsedUncles(blockStore, mineBest, true); knownUncles.addAll(ancestors); knownUncles.add(new ByteArrayWrapper(mineBest.getHash())); if (blockStore instanceof IndexedBlockStore) { outer: while (mineChain.getNumber() > limitNum) { List<Block> genBlocks = ((IndexedBlockStore) blockStore).getBlocksByNumber(mineChain.getNumber()); if (genBlocks.size() > 1) { for (Block uncleCandidate : genBlocks) { if (!knownUncles.contains(new ByteArrayWrapper(uncleCandidate.getHash())) && ancestors.contains(new ByteArrayWrapper(blockStore.getBlockByHash(uncleCandidate.getParentHash()).getHash()))) { ret.add(uncleCandidate.getHeader()); if (ret.size() >= UNCLE_LIST_LIMIT) { break outer; } } } } mineChain = blockStore.getBlockByHash(mineChain.getParentHash()); } } else { logger.warn("BlockStore is not instance of IndexedBlockStore: miner can't include uncles"); } return ret; } protected Block getNewBlockForMining() { Block bestBlockchain = blockchain.getBestBlock(); Block bestPendingState = ((PendingStateImpl) pendingState).getBestBlock(); logger.debug("getNewBlockForMining best blocks: PendingState: " + bestPendingState.getShortDescr() + ", Blockchain: " + bestBlockchain.getShortDescr()); Block newMiningBlock = blockchain.createNewBlock(bestPendingState, getAllPendingTransactions(), getUncles(bestPendingState)); return newMiningBlock; } protected void restartMining() { Block newMiningBlock = getNewBlockForMining(); synchronized(this) { cancelCurrentBlock(); miningBlock = newMiningBlock; if (externalMiner != null) { externalMiner.setListeners(listeners); currentMiningTasks.add(externalMiner.mine(cloneBlock(miningBlock))); } if (isLocalMining) { MinerIfc localMiner = config.getBlockchainConfig() .getConfigForBlock(miningBlock.getNumber()) .getMineAlgorithm(config); localMiner.setListeners(listeners); currentMiningTasks.add(localMiner.mine(cloneBlock(miningBlock))); } for (final ListenableFuture<MiningResult> task : currentMiningTasks) { task.addListener(() -> { try { // wow, block mined! final Block minedBlock = task.get().block; blockMined(minedBlock); } catch (InterruptedException | CancellationException e) { // OK, we've been cancelled, just exit } catch (Exception e) { logger.warn("Exception during mining: ", e); } }, MoreExecutors.directExecutor()); } } fireBlockStarted(newMiningBlock); logger.debug("New block mining started: {}", newMiningBlock.getShortHash()); } /** * Block cloning is required before passing block to concurrent miner env. * In success result miner will modify this block instance. */ private Block cloneBlock(Block block) { return new Block(block.getEncoded()); } protected void blockMined(Block newBlock) throws InterruptedException { long t = System.currentTimeMillis(); if (t - lastBlockMinedTime < minBlockTimeout) { long sleepTime = minBlockTimeout - (t - lastBlockMinedTime); logger.debug("Last block was mined " + (t - lastBlockMinedTime) + " ms ago. Sleeping " + sleepTime + " ms before importing..."); Thread.sleep(sleepTime); } fireBlockMined(newBlock); logger.info("Wow, block mined !!!: {}", newBlock.toString()); lastBlockMinedTime = t; miningBlock = null; // cancel all tasks cancelCurrentBlock(); // broadcast the block logger.debug("Importing newly mined block {} {} ...", newBlock.getShortHash(), newBlock.getNumber()); ImportResult importResult = ((EthereumImpl) ethereum).addNewMinedBlock(newBlock); logger.debug("Mined block import result is " + importResult); } public boolean isMining() { return isLocalMining || externalMiner != null; } /***** Listener boilerplate ******/ public void addListener(MinerListener l) { listeners.add(l); } public void removeListener(MinerListener l) { listeners.remove(l); } protected void fireMinerStarted() { for (MinerListener l : listeners) { l.miningStarted(); } } protected void fireMinerStopped() { for (MinerListener l : listeners) { l.miningStopped(); } } protected void fireBlockStarted(Block b) { for (MinerListener l : listeners) { l.blockMiningStarted(b); } } protected void fireBlockCancelled(Block b) { for (MinerListener l : listeners) { l.blockMiningCanceled(b); } } protected void fireBlockMined(Block b) { for (MinerListener l : listeners) { l.blockMined(b); } } }
13,435
36.116022
144
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashAlgo.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.crypto.HashUtil; import org.spongycastle.util.Arrays; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static java.lang.System.arraycopy; import static java.math.BigInteger.valueOf; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.*; import static org.spongycastle.util.Arrays.reverse; /** * The Ethash algorithm described in https://github.com/ethereum/wiki/wiki/Ethash * * Created by Anton Nashatyrev on 27.11.2015. */ public class EthashAlgo { EthashParams params; public EthashAlgo() { this(new EthashParams()); } public EthashAlgo(EthashParams params) { this.params = params; } public EthashParams getParams() { return params; } // Little-Endian ! static int getWord(byte[] arr, int wordOff) { return ByteBuffer.wrap(arr, wordOff * 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); } static void setWord(byte[] arr, int wordOff, long val) { ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) val); bb.rewind(); bb.get(arr, wordOff * 4, 4); } public static int remainderUnsigned(int dividend, int divisor) { if (divisor >= 0) { if (dividend >= 0) { return dividend % divisor; } // The implementation is a Java port of algorithm described in the book // "Hacker's Delight" (section "Unsigned short division from signed division"). int q = ((dividend >>> 1) / divisor) << 1; dividend -= q * divisor; if (dividend < 0 || dividend >= divisor) { dividend -= divisor; } return dividend; } return dividend >= 0 || dividend < divisor ? dividend : dividend - divisor; } private byte[][] makeCacheBytes(long cacheSize, byte[] seed) { int n = (int) (cacheSize / params.getHASH_BYTES()); byte[][] o = new byte[n][]; o[0] = HashUtil.sha512(seed); for (int i = 1; i < n; i++) { o[i] = HashUtil.sha512(o[i - 1]); } for (int cacheRound = 0; cacheRound < params.getCACHE_ROUNDS(); cacheRound++) { for (int i = 0; i < n; i++) { int v = remainderUnsigned(getWord(o[i], 0), n); o[i] = HashUtil.sha512(xor(o[(i - 1 + n) % n], o[v])); } } return o; } public int[] makeCache(long cacheSize, byte[] seed) { byte[][] bytes = makeCacheBytes(cacheSize, seed); int[] ret = new int[bytes.length * bytes[0].length / 4]; int[] ints = new int[bytes[0].length / 4]; for (int i = 0; i < bytes.length; i++) { bytesToInts(bytes[i], ints, false); arraycopy(ints, 0, ret, i * ints.length, ints.length); } return ret; } private static final int FNV_PRIME = 0x01000193; private static int fnv(int v1, int v2) { return (v1 * FNV_PRIME) ^ v2; } int[] sha512(int[] arr, boolean bigEndian) { byte[] bytesTmp = new byte[arr.length << 2]; intsToBytes(arr, bytesTmp, bigEndian); bytesTmp = HashUtil.sha512(bytesTmp); bytesToInts(bytesTmp, arr, bigEndian); return arr; } public final int[] calcDatasetItem(final int[] cache, final int i) { final int r = params.getHASH_BYTES() / params.getWORD_BYTES(); final int n = cache.length / r; int[] mix = Arrays.copyOfRange(cache, i % n * r, (i % n + 1) * r); mix[0] = i ^ mix[0]; mix = sha512(mix, false); final int dsParents = (int) params.getDATASET_PARENTS(); final int mixLen = mix.length; for (int j = 0; j < dsParents; j++) { int cacheIdx = fnv(i ^ j, mix[j % r]); cacheIdx = remainderUnsigned(cacheIdx, n); int off = cacheIdx * r; for (int k = 0; k < mixLen; k++) { mix[k] = fnv(mix[k], cache[off + k]); } } return sha512(mix, false); } public int[] calcDataset(long fullSize, int[] cache) { int hashesCount = (int) (fullSize / params.getHASH_BYTES()); int[] ret = new int[hashesCount * (params.getHASH_BYTES() / 4)]; for (int i = 0; i < hashesCount; i++) { int[] item = calcDatasetItem(cache, i); arraycopy(item, 0, ret, i * (params.getHASH_BYTES() / 4), item.length); } return ret; } public Pair<byte[], byte[]> hashimoto(byte[] blockHeaderTruncHash, byte[] nonce, long fullSize, int[] cacheOrDataset, boolean full) { if (nonce.length != 8) throw new RuntimeException("nonce.length != 8"); int hashWords = params.getHASH_BYTES() / 4; int w = params.getMIX_BYTES() / params.getWORD_BYTES(); int mixhashes = params.getMIX_BYTES() / params.getHASH_BYTES(); int[] s = bytesToInts(HashUtil.sha512(merge(blockHeaderTruncHash, reverse(nonce))), false); int[] mix = new int[params.getMIX_BYTES() / 4]; for (int i = 0; i < mixhashes; i++) { arraycopy(s, 0, mix, i * s.length, s.length); } int numFullPages = (int) (fullSize / params.getMIX_BYTES()); for (int i = 0; i < params.getACCESSES(); i++) { int p = remainderUnsigned(fnv(i ^ s[0], mix[i % w]), numFullPages); int[] newData = new int[mix.length]; int off = p * mixhashes; for (int j = 0; j < mixhashes; j++) { int itemIdx = off + j; if (!full) { int[] lookup1 = calcDatasetItem(cacheOrDataset, itemIdx); arraycopy(lookup1, 0, newData, j * lookup1.length, lookup1.length); } else { arraycopy(cacheOrDataset, itemIdx * hashWords, newData, j * hashWords, hashWords); } } for (int i1 = 0; i1 < mix.length; i1++) { mix[i1] = fnv(mix[i1], newData[i1]); } } int[] cmix = new int[mix.length / 4]; for (int i = 0; i < mix.length; i += 4 /* ? */) { int fnv1 = fnv(mix[i], mix[i + 1]); int fnv2 = fnv(fnv1, mix[i + 2]); int fnv3 = fnv(fnv2, mix[i + 3]); cmix[i >> 2] = fnv3; } return Pair.of(intsToBytes(cmix, false), sha3(merge(intsToBytes(s, false), intsToBytes(cmix, false)))); } public Pair<byte[], byte[]> hashimotoLight(long fullSize, final int[] cache, byte[] blockHeaderTruncHash, byte[] nonce) { return hashimoto(blockHeaderTruncHash, nonce, fullSize, cache, false); } public Pair<byte[], byte[]> hashimotoFull(long fullSize, final int[] dataset, byte[] blockHeaderTruncHash, byte[] nonce) { return hashimoto(blockHeaderTruncHash, nonce, fullSize, dataset, true); } public long mine(long fullSize, int[] dataset, byte[] blockHeaderTruncHash, long difficulty) { return mine(fullSize, dataset, blockHeaderTruncHash, difficulty, new Random().nextLong()); } public long mine(long fullSize, int[] dataset, byte[] blockHeaderTruncHash, long difficulty, long startNonce) { long nonce = startNonce; BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty)); while (!Thread.currentThread().isInterrupted()) { nonce++; Pair<byte[], byte[]> pair = hashimotoFull(fullSize, dataset, blockHeaderTruncHash, longToBytes(nonce)); BigInteger h = new BigInteger(1, pair.getRight() /* ?? */); if (h.compareTo(target) < 0) break; } return nonce; } /** * This the slower miner version which uses only cache thus taking much less memory than * regular {@link #mine} method */ public long mineLight(long fullSize, final int[] cache, byte[] blockHeaderTruncHash, long difficulty) { return mineLight(fullSize, cache, blockHeaderTruncHash, difficulty, new Random().nextLong()); } public long mineLight(long fullSize, final int[] cache, byte[] blockHeaderTruncHash, long difficulty, long startNonce) { long nonce = startNonce; BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty)); while(!Thread.currentThread().isInterrupted()) { nonce++; Pair<byte[], byte[]> pair = hashimotoLight(fullSize, cache, blockHeaderTruncHash, longToBytes(nonce)); BigInteger h = new BigInteger(1, pair.getRight() /* ?? */); if (h.compareTo(target) < 0) break; } return nonce; } public byte[] getSeedHash(long blockNumber) { byte[] ret = new byte[32]; for (int i = 0; i < blockNumber / params.getEPOCH_LENGTH(); i++) { ret = sha3(ret); } return ret; } }
9,911
38.333333
124
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/MinerIfc.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import java.util.Collection; /** * Mine algorithm interface * * Created by Anton Nashatyrev on 25.02.2016. */ public interface MinerIfc { /** * Starts mining the block. On successful mining the Block is update with necessary nonce and hash. * @return MiningResult Future object. The mining can be canceled via this Future. The Future is complete * when the block successfully mined. */ ListenableFuture<MiningResult> mine(Block block); /** * Validates the Proof of Work for the block */ boolean validate(BlockHeader blockHeader); /** * Passes {@link MinerListener}'s to miner */ void setListeners(Collection<MinerListener> listeners); final class MiningResult { public final long nonce; public final byte[] digest; /** * Mined block */ public final Block block; public MiningResult(long nonce, byte[] digest, Block block) { this.nonce = nonce; this.digest = digest; this.block = block; } } }
2,027
28.823529
109
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/Ethash.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Collection; import java.util.Random; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.mine.EthashListener.DatasetStatus.DATASET_READY; import static org.ethereum.mine.EthashListener.DatasetStatus.DATASET_PREPARE; import static org.ethereum.mine.EthashListener.DatasetStatus.FULL_DATASET_GENERATED; import static org.ethereum.mine.EthashListener.DatasetStatus.FULL_DATASET_GENERATE_START; import static org.ethereum.mine.EthashListener.DatasetStatus.FULL_DATASET_LOADED; import static org.ethereum.mine.EthashListener.DatasetStatus.FULL_DATASET_LOAD_START; import static org.ethereum.mine.EthashListener.DatasetStatus.LIGHT_DATASET_GENERATED; import static org.ethereum.mine.EthashListener.DatasetStatus.LIGHT_DATASET_GENERATE_START; import static org.ethereum.mine.EthashListener.DatasetStatus.LIGHT_DATASET_LOADED; import static org.ethereum.mine.EthashListener.DatasetStatus.LIGHT_DATASET_LOAD_START; import static org.ethereum.util.ByteUtil.longToBytes; import static org.ethereum.mine.MinerIfc.MiningResult; /** * More high level validator/miner class which keeps a cache for the last requested block epoch * * Created by Anton Nashatyrev on 04.12.2015. */ public class Ethash { private static final Logger logger = LoggerFactory.getLogger("mine"); static EthashParams ethashParams = new EthashParams(); static Ethash cachedInstance = null; long epoch = 0; // private static ExecutorService executor = Executors.newSingleThreadExecutor(); private static ListeningExecutorService executor = MoreExecutors.listeningDecorator( new ThreadPoolExecutor(8, 8, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("ethash-pool-%d").build())); public static boolean fileCacheEnabled = true; private Set<EthashListener> listeners = new CopyOnWriteArraySet <>(); /** * Returns instance for the specified block number * either from cache or calculates a new one */ public static Ethash getForBlock(SystemProperties config, long blockNumber) { long epoch = blockNumber / ethashParams.getEPOCH_LENGTH(); if (cachedInstance == null || epoch != cachedInstance.epoch) { cachedInstance = new Ethash(config, epoch * ethashParams.getEPOCH_LENGTH()); } return cachedInstance; } /** * Returns instance for the specified block number * either from cache or calculates a new one * and adds listeners to Ethash */ public static Ethash getForBlock(SystemProperties config, long blockNumber, Collection<EthashListener> listeners) { Ethash ethash = getForBlock(config, blockNumber); ethash.listeners.clear(); ethash.listeners.addAll(listeners); return ethash; } private EthashAlgo ethashAlgo = new EthashAlgo(ethashParams); private long blockNumber; private int[] cacheLight = null; private int[] fullData = null; private SystemProperties config; private long startNonce = -1; public Ethash(SystemProperties config, long blockNumber) { this.config = config; this.blockNumber = blockNumber; this.epoch = blockNumber / ethashAlgo.getParams().getEPOCH_LENGTH(); if (config.getConfig().hasPath("mine.startNonce")) { startNonce = config.getConfig().getLong("mine.startNonce"); } } public synchronized int[] getCacheLight() { if (cacheLight == null) { fireDatatasetStatusUpdate(DATASET_PREPARE); getCacheLightImpl(); fireDatatasetStatusUpdate(DATASET_READY); } return cacheLight; } /** * Checks whether light DAG is already generated and loads it * from cache, otherwise generates it * @return Light DAG */ private synchronized int[] getCacheLightImpl() { if (cacheLight == null) { File file = new File(config.ethashDir(), "mine-dag-light.dat"); if (fileCacheEnabled && file.canRead()) { fireDatatasetStatusUpdate(LIGHT_DATASET_LOAD_START); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { logger.info("Loading light dataset from " + file.getAbsolutePath()); long bNum = ois.readLong(); if (bNum == blockNumber) { cacheLight = (int[]) ois.readObject(); fireDatatasetStatusUpdate(LIGHT_DATASET_LOADED); logger.info("Dataset loaded."); } else { logger.info("Dataset block number miss: " + bNum + " != " + blockNumber); } } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } if (cacheLight == null) { logger.info("Calculating light dataset..."); fireDatatasetStatusUpdate(LIGHT_DATASET_GENERATE_START); cacheLight = getEthashAlgo().makeCache(getEthashAlgo().getParams().getCacheSize(blockNumber), getEthashAlgo().getSeedHash(blockNumber)); logger.info("Light dataset calculated."); if (fileCacheEnabled) { file.getParentFile().mkdirs(); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){ logger.info("Writing light dataset to " + file.getAbsolutePath()); oos.writeLong(blockNumber); oos.writeObject(cacheLight); } catch (IOException e) { throw new RuntimeException(e); } } fireDatatasetStatusUpdate(LIGHT_DATASET_GENERATED); } } return cacheLight; } public synchronized int[] getFullDataset() { if (fullData == null) { fireDatatasetStatusUpdate(DATASET_PREPARE); File file = new File(config.ethashDir(), "mine-dag.dat"); if (fileCacheEnabled && file.canRead()) { fireDatatasetStatusUpdate(FULL_DATASET_LOAD_START); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { logger.info("Loading dataset from " + file.getAbsolutePath()); long bNum = ois.readLong(); if (bNum == blockNumber) { fullData = (int[]) ois.readObject(); logger.info("Dataset loaded."); fireDatatasetStatusUpdate(FULL_DATASET_LOADED); } else { logger.info("Dataset block number miss: " + bNum + " != " + blockNumber); } } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(e); } } if (fullData == null){ logger.info("Calculating full dataset..."); fireDatatasetStatusUpdate(FULL_DATASET_GENERATE_START); int[] cacheLight = getCacheLightImpl(); fullData = getEthashAlgo().calcDataset(getFullSize(), cacheLight); logger.info("Full dataset calculated."); if (fileCacheEnabled) { file.getParentFile().mkdirs(); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { logger.info("Writing dataset to " + file.getAbsolutePath()); oos.writeLong(blockNumber); oos.writeObject(fullData); } catch (IOException e) { throw new RuntimeException(e); } } fireDatatasetStatusUpdate(FULL_DATASET_GENERATED); } fireDatatasetStatusUpdate(DATASET_READY); } return fullData; } int[] getFullData() { return fullData; } private long getFullSize() { return getEthashAlgo().getParams().getFullSize(blockNumber); } private EthashAlgo getEthashAlgo() { return ethashAlgo; } /** * See {@link EthashAlgo#hashimotoLight} */ public Pair<byte[], byte[]> hashimotoLight(BlockHeader header, long nonce) { return hashimotoLight(header, longToBytes(nonce)); } private Pair<byte[], byte[]> hashimotoLight(BlockHeader header, byte[] nonce) { return getEthashAlgo().hashimotoLight(getFullSize(), getCacheLight(), sha3(header.getEncodedWithoutNonce()), nonce); } /** * See {@link EthashAlgo#hashimotoFull} */ public Pair<byte[], byte[]> hashimotoFull(BlockHeader header, long nonce) { return getEthashAlgo().hashimotoFull(getFullSize(), getFullDataset(), sha3(header.getEncodedWithoutNonce()), longToBytes(nonce)); } public ListenableFuture<MiningResult> mine(final Block block) { return mine(block, 1); } /** * Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty() * When mined the Block 'nonce' and 'mixHash' fields are updated * Uses the full dataset i.e. it faster but takes > 1Gb of memory and may * take up to 10 mins for starting up (depending on whether the dataset was cached) * * @param block The block to mine. The difficulty is taken from the block header * This block is updated when mined * @param nThreads CPU threads to mine on * @return the task which may be cancelled. On success returns nonce */ public ListenableFuture<MiningResult> mine(final Block block, int nThreads) { return new MineTask(block, nThreads, new Callable<MiningResult>() { AtomicLong taskStartNonce = new AtomicLong(startNonce >= 0 ? startNonce : new Random().nextLong()); @Override public MiningResult call() throws Exception { long threadStartNonce = taskStartNonce.getAndAdd(0x100000000L); long nonce = getEthashAlgo().mine(getFullSize(), getFullDataset(), sha3(block.getHeader().getEncodedWithoutNonce()), ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()), threadStartNonce); final Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), nonce); return new MiningResult(nonce, pair.getLeft(), block); } }).submit(); } public ListenableFuture<MiningResult> mineLight(final Block block) { return mineLight(block, 1); } /** * Mines the nonce for the specified Block with difficulty BlockHeader.getDifficulty() * When mined the Block 'nonce' and 'mixHash' fields are updated * Uses the light cache i.e. it slower but takes only ~16Mb of memory and takes less * time to start up * * @param block The block to mine. The difficulty is taken from the block header * This block is updated when mined * @param nThreads CPU threads to mine on * @return the task which may be cancelled. On success returns nonce */ public ListenableFuture<MiningResult> mineLight(final Block block, int nThreads) { return new MineTask(block, nThreads, new Callable<MiningResult>() { AtomicLong taskStartNonce = new AtomicLong(startNonce >= 0 ? startNonce : new Random().nextLong()); @Override public MiningResult call() throws Exception { long threadStartNonce = taskStartNonce.getAndAdd(0x100000000L); final long nonce = getEthashAlgo().mineLight(getFullSize(), getCacheLight(), sha3(block.getHeader().getEncodedWithoutNonce()), ByteUtil.byteArrayToLong(block.getHeader().getDifficulty()), threadStartNonce); final Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), nonce); return new MiningResult(nonce, pair.getLeft(), block); } }).submit(); } /** * Validates the BlockHeader against its getDifficulty() and getNonce() */ public boolean validate(BlockHeader header) { byte[] boundary = header.getPowBoundary(); byte[] hash = hashimotoLight(header, header.getNonce()).getRight(); return FastByteComparisons.compareTo(hash, 0, 32, boundary, 0, 32) < 0; } private void fireDatatasetStatusUpdate(EthashListener.DatasetStatus status) { for (EthashListener l : listeners) { l.onDatasetUpdate(status); } } class MineTask extends AnyFuture<MiningResult> { Block block; int nThreads; Callable<MiningResult> miner; public MineTask(Block block, int nThreads, Callable<MiningResult> miner) { this.block = block; this.nThreads = nThreads; this.miner = miner; } public MineTask submit() { for (int i = 0; i < nThreads; i++) { ListenableFuture<MiningResult> f = executor.submit(miner); add(f); } return this; } @Override protected void postProcess(MiningResult result) { Pair<byte[], byte[]> pair = hashimotoLight(block.getHeader(), result.nonce); block.setNonce(longToBytes(result.nonce)); block.setMixHash(pair.getLeft()); } } }
15,191
41.915254
119
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; /** * {@link MinerListener} designed for use with {@link EthashMiner} */ public interface EthashListener extends MinerListener { enum DatasetStatus { /** * Dataset requested and will be prepared */ DATASET_PREPARE, /** * Indicates start of light DAG generation * If full dataset is requested, its event * {@link #FULL_DATASET_GENERATE_START} fires before this one */ LIGHT_DATASET_GENERATE_START, /** * Indicates that light dataset is already generated * and will be loaded from disk though it could be outdated * and therefore {@link #LIGHT_DATASET_LOADED} will not be fired */ LIGHT_DATASET_LOAD_START, /** * Indicates end of loading light dataset from disk */ LIGHT_DATASET_LOADED, /** * Indicates finish of light dataset generation */ LIGHT_DATASET_GENERATED, /** * Indicates start of full DAG generation * Full DAG generation is a heavy procedure * which could take a lot of time. * Also full dataset requires light dataset * so it will be either generated or loaded from * disk as part of this job */ FULL_DATASET_GENERATE_START, /** * Indicates that full dataset is already generated * and will be loaded from disk though it could be outdated * and therefore {@link #FULL_DATASET_LOADED} will not be fired */ FULL_DATASET_LOAD_START, /** * Indicates end of full dataset loading from disk */ FULL_DATASET_LOADED, /** * Indicates finish of full dataset generation */ FULL_DATASET_GENERATED, /** * Requested dataset is complete and ready for use */ DATASET_READY, } void onDatasetUpdate(DatasetStatus datasetStatus); }
2,796
33.530864
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashAlgoSlow.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.apache.commons.lang3.tuple.Pair; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static java.lang.System.arraycopy; import static java.math.BigInteger.valueOf; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.crypto.HashUtil.sha512; import static org.ethereum.util.ByteUtil.*; import static org.spongycastle.util.Arrays.reverse; /** * The Ethash algorithm described in https://github.com/ethereum/wiki/wiki/Ethash * * This is the non-optimized Ethash implementation. It is left here for reference only * since the non-optimized version is slightly better for understanding the Ethash algorithm * * Created by Anton Nashatyrev on 27.11.2015. * @deprecated Use a faster version {@link EthashAlgo}, this class is for reference only */ public class EthashAlgoSlow { EthashParams params; public EthashAlgoSlow() { this(new EthashParams()); } public EthashAlgoSlow(EthashParams params) { this.params = params; } public EthashParams getParams() { return params; } // Little-Endian ! static long getWord(byte[] arr, int wordOff) { return ByteBuffer.wrap(arr, wordOff * 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL; } static void setWord(byte[] arr, int wordOff, long val) { ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt((int) val); bb.rewind(); bb.get(arr, wordOff * 4, 4); } public byte[][] makeCache(long cacheSize, byte[] seed) { int n = (int) (cacheSize / params.getHASH_BYTES()); byte[][] o = new byte[n][]; o[0] = sha512(seed); for (int i = 1; i < n; i++) { o[i] = sha512(o[i - 1]); } for (int cacheRound = 0; cacheRound < params.getCACHE_ROUNDS(); cacheRound++) { for (int i = 0; i < n; i++) { int v = (int) (getWord(o[i], 0) % n); o[i] = sha512(xor(o[(i - 1 + n) % n], o[v])); } } return o; } private static final long FNV_PRIME = 0x01000193; long fnv(long v1, long v2) { return ((v1 * FNV_PRIME) ^ v2) % (1L << 32); } byte[] fnv(byte[] b1, byte[] b2) { if (b1.length != b2.length || b1.length % 4 != 0) throw new RuntimeException(); byte[] ret = new byte[b1.length]; for (int i = 0; i < b1.length / 4; i++) { long i1 = getWord(b1, i); long i2 = getWord(b2, i); setWord(ret, i, fnv(i1, i2)); } return ret; } public byte[] calcDatasetItem(byte[][] cache, int i) { int n = cache.length; int r = params.getHASH_BYTES() / params.getWORD_BYTES(); byte[] mix = cache[i % n].clone(); setWord(mix, 0, i ^ getWord(mix, 0)); mix = sha512(mix); for (int j = 0; j < params.getDATASET_PARENTS(); j++) { long cacheIdx = fnv(i ^ j, getWord(mix, j % r)); mix = fnv(mix, cache[(int) (cacheIdx % n)]); } return sha512(mix); } public byte[][] calcDataset(long fullSize, byte[][] cache) { byte[][] ret = new byte[(int) (fullSize / params.getHASH_BYTES())][]; for (int i = 0; i < ret.length; i++) { ret[i] = calcDatasetItem(cache, i); } return ret; } public Pair<byte[], byte[]> hashimoto(byte[] blockHeaderTruncHash, byte[] nonce, long fullSize, DatasetLookup lookup) { // if (nonce.length != 4) throw new RuntimeException("nonce.length != 4"); int w = params.getMIX_BYTES() / params.getWORD_BYTES(); int mixhashes = params.getMIX_BYTES() / params.getHASH_BYTES(); byte[] s = sha512(merge(blockHeaderTruncHash, reverse(nonce))); byte[] mix = new byte[params.getMIX_BYTES()]; for (int i = 0; i < mixhashes; i++) { arraycopy(s, 0, mix, i * s.length, s.length); } int numFullPages = (int) (fullSize / params.getMIX_BYTES()); for (int i = 0; i < params.getACCESSES(); i++) { long p = fnv(i ^ getWord(s, 0), getWord(mix, i % w)) % numFullPages; byte[] newData = new byte[params.getMIX_BYTES()]; for (int j = 0; j < mixhashes; j++) { byte[] lookup1 = lookup.lookup((int) (p * mixhashes + j)); arraycopy(lookup1, 0, newData, j * lookup1.length, lookup1.length); } mix = fnv(mix, newData); } byte[] cmix = new byte[mix.length / 4]; for (int i = 0; i < mix.length / 4; i += 4 /* ? */) { long fnv1 = fnv(getWord(mix, i), getWord(mix, i + 1)); long fnv2 = fnv(fnv1, getWord(mix, i + 2)); long fnv3 = fnv(fnv2, getWord(mix, i + 3)); setWord(cmix, i / 4, fnv3); } return Pair.of(cmix, sha3(merge(s, cmix))); } public Pair<byte[], byte[]> hashimotoLight(long fullSize, final byte[][] cache, byte[] blockHeaderTruncHash, byte[] nonce) { return hashimoto(blockHeaderTruncHash, nonce, fullSize, new DatasetLookup() { @Override public byte[] lookup(int idx) { return calcDatasetItem(cache, idx); } }); } public Pair<byte[], byte[]> hashimotoFull(long fullSize, final byte[][] dataset, byte[] blockHeaderTruncHash, byte[] nonce) { return hashimoto(blockHeaderTruncHash, nonce, fullSize, new DatasetLookup() { @Override public byte[] lookup(int idx) { return dataset[idx]; } }); } public long mine(long fullSize, byte[][] dataset, byte[] blockHeaderTruncHash, long difficulty) { BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty)); long nonce = new Random().nextLong(); while(!Thread.currentThread().isInterrupted()) { nonce++; Pair<byte[], byte[]> pair = hashimotoFull(fullSize, dataset, blockHeaderTruncHash, longToBytes(nonce)); BigInteger h = new BigInteger(1, pair.getRight() /* ?? */); if (h.compareTo(target) < 0) break; } return nonce; } /** * This the slower miner version which uses only cache thus taking much less memory than * regular {@link #mine} method */ public long mineLight(long fullSize, final byte[][] cache, byte[] blockHeaderTruncHash, long difficulty) { BigInteger target = valueOf(2).pow(256).divide(valueOf(difficulty)); long nonce = new Random().nextLong(); while(!Thread.currentThread().isInterrupted()) { nonce++; Pair<byte[], byte[]> pair = hashimotoLight(fullSize, cache, blockHeaderTruncHash, longToBytes(nonce)); BigInteger h = new BigInteger(1, pair.getRight() /* ?? */); if (h.compareTo(target) < 0) break; } return nonce; } public byte[] getSeedHash(long blockNumber) { byte[] ret = new byte[32]; for (int i = 0; i < blockNumber / params.getEPOCH_LENGTH(); i++) { ret = sha3(ret); } return ret; } private interface DatasetLookup { byte[] lookup(int idx); } }
8,169
36.64977
123
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashParams.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; /** * Created by Anton Nashatyrev on 27.11.2015. */ public class EthashParams { // bytes in word private final int WORD_BYTES = 4; // bytes in dataset at genesis private final long DATASET_BYTES_INIT = 1L << 30; // dataset growth per epoch private final long DATASET_BYTES_GROWTH = 1L << 23; // bytes in dataset at genesis private final long CACHE_BYTES_INIT = 1L << 24; // cache growth per epoch private final long CACHE_BYTES_GROWTH = 1L << 17; // Size of the DAG relative to the cache private final long CACHE_MULTIPLIER = 1024; // blocks per epoch private final long EPOCH_LENGTH = 30000; // width of mix private final int MIX_BYTES = 128; // hash length in bytes private final int HASH_BYTES = 64; // number of parents of each dataset element private final long DATASET_PARENTS = 256; // number of rounds in cache production private final long CACHE_ROUNDS = 3; // number of accesses in hashimoto loop private final long ACCESSES = 64; /** * The parameters for Ethash's cache and dataset depend on the block number. * The cache size and dataset size both grow linearly; however, we always take the highest * prime below the linearly growing threshold in order to reduce the risk of accidental * regularities leading to cyclic behavior. */ public long getCacheSize(long blockNumber) { long sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * (blockNumber / EPOCH_LENGTH); sz -= HASH_BYTES; while (!isPrime(sz / HASH_BYTES)) { sz -= 2 * HASH_BYTES; } return sz; } public long getFullSize(long blockNumber) { long sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * (blockNumber / EPOCH_LENGTH); sz -= MIX_BYTES; while (!isPrime(sz / MIX_BYTES)) { sz -= 2 * MIX_BYTES; } return sz; } private static boolean isPrime(long num) { if (num == 2) return true; if (num % 2 == 0) return false; for (int i = 3; i * i < num; i += 2) if (num % i == 0) return false; return true; } public int getWORD_BYTES() { return WORD_BYTES; } public long getDATASET_BYTES_INIT() { return DATASET_BYTES_INIT; } public long getDATASET_BYTES_GROWTH() { return DATASET_BYTES_GROWTH; } public long getCACHE_BYTES_INIT() { return CACHE_BYTES_INIT; } public long getCACHE_BYTES_GROWTH() { return CACHE_BYTES_GROWTH; } public long getCACHE_MULTIPLIER() { return CACHE_MULTIPLIER; } public long getEPOCH_LENGTH() { return EPOCH_LENGTH; } public int getMIX_BYTES() { return MIX_BYTES; } public int getHASH_BYTES() { return HASH_BYTES; } public long getDATASET_PARENTS() { return DATASET_PARENTS; } public long getCACHE_ROUNDS() { return CACHE_ROUNDS; } public long getACCESSES() { return ACCESSES; } }
3,902
26.680851
94
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashMiner.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import java.util.Collection; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * The adapter of Ethash for MinerIfc * * Created by Anton Nashatyrev on 26.02.2016. */ public class EthashMiner implements MinerIfc { SystemProperties config; private int cpuThreads; private boolean fullMining = true; private Set<EthashListener> listeners = new CopyOnWriteArraySet<>(); public EthashMiner(SystemProperties config) { this.config = config; cpuThreads = config.getMineCpuThreads(); fullMining = config.isMineFullDataset(); } @Override public ListenableFuture<MiningResult> mine(Block block) { return fullMining ? Ethash.getForBlock(config, block.getNumber(), listeners).mine(block, cpuThreads) : Ethash.getForBlock(config, block.getNumber(), listeners).mineLight(block, cpuThreads); } @Override public boolean validate(BlockHeader blockHeader) { return Ethash.getForBlock(config, blockHeader.getNumber(), listeners).validate(blockHeader); } /** * Listeners changes affects only future {@link #mine(Block)} and * {@link #validate(BlockHeader)} calls * Only instances of {@link EthashListener} are used, because EthashMiner * produces only events compatible with it */ @Override public void setListeners(Collection<MinerListener> listeners) { this.listeners.clear(); listeners.stream() .filter(listener -> listener instanceof EthashListener) .map(listener -> (EthashListener) listener) .forEach(this.listeners::add); } }
2,666
34.56
102
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/AnyFuture.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.AbstractFuture; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import java.util.ArrayList; import java.util.List; /** * Future completes when any of child futures completed. All others are cancelled * upon completion. */ public class AnyFuture<V> extends AbstractFuture<V> { private List<ListenableFuture<V>> futures = new ArrayList<>(); /** * Add a Future delegate */ public synchronized void add(final ListenableFuture<V> f) { if (isCancelled() || isDone()) return; f.addListener(() -> futureCompleted(f), MoreExecutors.directExecutor()); futures.add(f); } private synchronized void futureCompleted(ListenableFuture<V> f) { if (isCancelled() || isDone()) return; if (f.isCancelled()) return; try { cancelOthers(f); V v = f.get(); postProcess(v); set(v); } catch (Exception e) { setException(e); } } /** * Subclasses my override to perform some task on the calculated * value before returning it via Future */ protected void postProcess(V v) {} private void cancelOthers(ListenableFuture besidesThis) { for (ListenableFuture future : futures) { if (future != besidesThis) { try { future.cancel(true); } catch (Exception e) { } } } } @Override protected void interruptTask() { cancelOthers(null); } }
2,473
29.54321
82
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/MinerListener.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.ethereum.core.Block; /** * Created by Anton Nashatyrev on 10.12.2015. */ public interface MinerListener { void miningStarted(); void miningStopped(); void blockMiningStarted(Block block); void blockMined(Block block); void blockMiningCanceled(Block block); }
1,111
33.75
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.ethereum.core.Block; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.Arrays; import org.spongycastle.util.BigIntegers; import java.math.BigInteger; import static org.ethereum.crypto.HashUtil.sha3; /** * The Miner performs the proof-of-work needed for a valid block * * The mining proof-of-work (PoW) exists as a cryptographically secure nonce * that proves beyond reasonable doubt that a particular amount of computation * has been expended in the determination of some token value n. * It is utilised to enforce the blockchain security by giving meaning * and credence to the notion of difficulty (and, by extension, total difficulty). * * However, since mining new blocks comes with an attached reward, * the proof-of-work not only functions as a method of securing confidence * that the blockchain will remain canonical into the future, but also as * a wealth distribution mechanism. * * See Yellow Paper: http://www.gavwood.com/Paper.pdf (chapter 11.5 Mining Proof-of-Work) */ public class Miner { private static final Logger logger = LoggerFactory.getLogger("miner"); private boolean stop = false; /** * Adds a nonce to given block which complies with the given difficulty * * For the PoC series, we use a simplified proof-of-work. * This is not ASIC resistant and is meant merely as a placeholder. * It utilizes the bare SHA3 hash function to secure the block chain by requiring * the SHA3 hash of the concatenation of the nonce and the header’s SHA3 hash to be * sufficiently low. It is formally defined as PoW: * * PoW(H, n) ≡ BE(SHA3(SHA3(RLP(H!n)) ◦ n)) * * where: * RLP(H!n) is the RLP encoding of the block header H, not including the * final nonce component; * SHA3 is the SHA3 hash function accepting an arbitrary length series of * bytes and evaluating to a series of 32 bytes (i.e. 256-bit); * n is the nonce, a series of 32 bytes; * o is the series concatenation operator; * BE(X) evaluates to the value equal to X when interpreted as a * big-endian-encoded integer. * * @param newBlock without a valid nonce * @param difficulty - the mining difficulty * @return true if valid nonce has been added to the block */ public boolean mine(Block newBlock, byte[] difficulty) { // eval(_root, _nonce) <= (bigint(1) << 256) / _difficulty; } stop = false; BigInteger max = BigInteger.valueOf(2).pow(255); byte[] target = BigIntegers.asUnsignedByteArray(32, max.divide(new BigInteger(1, difficulty))); long newGasLimit = Math.max(125000, (new BigInteger(1, newBlock.getGasLimit()).longValue() * (1024 - 1) + (newBlock.getGasUsed() * 6 / 5)) / 1024); newBlock.getHeader().setGasLimit(BigInteger.valueOf(newGasLimit).toByteArray()); byte[] hash = sha3(newBlock.getEncodedWithoutNonce()); byte[] testNonce = new byte[32]; byte[] concat; while (ByteUtil.increment(testNonce) && !stop) { if (testNonce[31] == 0 && testNonce[30] == 0) { System.out.println("mining: " + new BigInteger(1, testNonce)); } if (testNonce[31] == 0) sleep(); concat = Arrays.concatenate(hash, testNonce); byte[] result = sha3(concat); if (FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0) { newBlock.setNonce(testNonce); return true; } } return false; // couldn't find a valid nonce } public void stop() { stop = true; } private void sleep() { try { // Thread.sleep(1); Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }
4,880
36.259542
127
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/mine/EthashValidationHelper.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.Constants; import org.ethereum.core.BlockHeader; import org.ethereum.crypto.HashUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Maintains datasets of {@link EthashAlgo} for verification purposes. * * <p> * Takes a burden of light dataset caching and provides convenient interface for keeping this cache up to date. * Featured with full dataset lookup if such dataset is available (created for mining purposes), * full dataset usage increases verification speed dramatically. * * <p> * Entry point is {@link #ethashWorkFor(BlockHeader, byte[], boolean)} * * <p> * Cache management interface: {@link #preCache(long)}, {@link CacheOrder} * * @author Mikhail Kalinin * @since 20.06.2018 */ public class EthashValidationHelper { private static final int MAX_CACHED_EPOCHS = 2; private static final Logger logger = LoggerFactory.getLogger("ethash"); public enum CacheOrder { direct, /** cache is updated to fit main import process, toward big numbers */ reverse /** for maintaining reverse header validation, cache is updated to fit block validation with decreasing numbers */ } List<Cache> caches = new CopyOnWriteArrayList<>(); EthashAlgo ethashAlgo = new EthashAlgo(Ethash.ethashParams); long lastCachedEpoch = -1; private CacheStrategy cacheStrategy; private static ExecutorService executor; public EthashValidationHelper(CacheOrder cacheOrder) { this.cacheStrategy = createCacheStrategy(cacheOrder); if (executor == null) executor = Executors.newSingleThreadExecutor((r) -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setName("ethash-validation-helper"); t.setDaemon(true); return t; }); } /** * Calculates ethash results for particular block and nonce. * * @param cachedOnly flag that defined behavior of method when dataset has not been cached: * if set to true - returns null immediately * if set to false - generates dataset for block epoch and then runs calculations on it */ public Pair<byte[], byte[]> ethashWorkFor(BlockHeader header, byte[] nonce, boolean cachedOnly) throws Exception { long fullSize = ethashAlgo.getParams().getFullSize(header.getNumber()); byte[] hashWithoutNonce = HashUtil.sha3(header.getEncodedWithoutNonce()); // lookup with full dataset if it's available Ethash cachedInstance = Ethash.cachedInstance; if (cachedInstance != null && cachedInstance.epoch == epoch(header.getNumber()) && cachedInstance.getFullData() != null) { return ethashAlgo.hashimotoFull(fullSize, cachedInstance.getFullData(), hashWithoutNonce, nonce); } Cache cache = getCachedFor(header.getNumber()); if (cache != null) { return ethashAlgo.hashimotoLight(fullSize, cache.getDataset(), hashWithoutNonce, nonce); } else if (!cachedOnly) { cache = new Cache(header.getNumber()); return ethashAlgo.hashimotoLight(fullSize, cache.getDataset(), hashWithoutNonce, nonce); } else { return null; } } Cache getCachedFor(long blockNumber) { for (Cache cache : caches) { if (cache.isFor(blockNumber)) return cache; } return null; } public void preCache(long blockNumber) { cacheStrategy.cache(blockNumber); } long epochLength() { return ethashAlgo.getParams().getEPOCH_LENGTH(); } long epoch(long blockNumber) { return blockNumber / ethashAlgo.getParams().getEPOCH_LENGTH(); } class Cache { CompletableFuture<int[]> dataset; long epoch; Cache(long blockNumber) { byte[] seed = ethashAlgo.getSeedHash(blockNumber); long size = ethashAlgo.getParams().getCacheSize(blockNumber); this.dataset = new CompletableFuture<>(); executor.submit(() -> { int[] cache = ethashAlgo.makeCache(size, seed); this.dataset.complete(cache); }); this.epoch = epoch(blockNumber); } boolean isFor(long blockNumber) { return epoch == epoch(blockNumber); } int[] getDataset() throws Exception { return dataset.get(); } } private CacheStrategy createCacheStrategy(CacheOrder order) { switch (order) { case direct: return new DirectCache(); case reverse: return new ReverseCache(); default: throw new IllegalArgumentException("Unsupported cache strategy " + order.name()); } } interface CacheStrategy { void cache(long blockNumber); } class ReverseCache implements CacheStrategy { @Override public void cache(long blockNumber) { // reset cache if it's outdated if (epoch(blockNumber) < lastCachedEpoch || lastCachedEpoch < 0) { reset(blockNumber); return; } // lock-free check if (blockNumber < epochLength() || epoch(blockNumber) - 1 >= lastCachedEpoch || blockNumber % epochLength() >= epochLength() / 2) return; synchronized (EthashValidationHelper.this) { if (blockNumber < epochLength() || epoch(blockNumber) - 1 >= lastCachedEpoch || blockNumber % epochLength() >= epochLength() / 2) return; // cache previous epoch caches.add(new Cache(blockNumber - epochLength())); lastCachedEpoch -= 1; // remove redundant caches while (caches.size() > MAX_CACHED_EPOCHS) caches.remove(0); logger.info("Kept caches: cnt: {} epochs: {}...{}", caches.size(), caches.get(0).epoch, caches.get(caches.size() - 1).epoch); } } private void reset(long blockNumber) { synchronized (EthashValidationHelper.this) { caches.clear(); caches.add(new Cache(blockNumber)); if (blockNumber % epochLength() >= epochLength() / 2) { caches.add(0, new Cache(blockNumber + epochLength())); } else if (blockNumber >= epochLength()) { caches.add(new Cache(blockNumber - epochLength())); } lastCachedEpoch = caches.get(caches.size() - 1).epoch; logger.info("Kept caches: cnt: {} epochs: {}...{}", caches.size(), caches.get(0).epoch, caches.get(caches.size() - 1).epoch); } } } class DirectCache implements CacheStrategy { @Override public void cache(long blockNumber) { // reset cache if it's outdated if (epoch(blockNumber) > lastCachedEpoch || lastCachedEpoch < 0) { reset(blockNumber); return; } // lock-free check if (epoch(blockNumber) + 1 <= lastCachedEpoch || blockNumber % epochLength() <= Constants.getLONGEST_CHAIN()) return; synchronized (EthashValidationHelper.this) { if (epoch(blockNumber) + 1 <= lastCachedEpoch || blockNumber % epochLength() <= Constants.getLONGEST_CHAIN()) return; // cache next epoch caches.add(new Cache(blockNumber + epochLength())); lastCachedEpoch += 1; // remove redundant caches while (caches.size() > MAX_CACHED_EPOCHS) caches.remove(0); logger.info("Kept caches: cnt: {} epochs: {}...{}", caches.size(), caches.get(0).epoch, caches.get(caches.size() - 1).epoch); } } private void reset(long blockNumber) { synchronized (EthashValidationHelper.this) { caches.clear(); caches.add(new Cache(blockNumber)); if (blockNumber % epochLength() > Constants.getLONGEST_CHAIN()) { caches.add(new Cache(blockNumber + epochLength())); } else if (blockNumber >= epochLength()) { caches.add(0, new Cache(blockNumber - epochLength())); } lastCachedEpoch = caches.get(caches.size() - 1).epoch; logger.info("Kept caches: cnt: {} epochs: {}...{}", caches.size(), caches.get(0).epoch, caches.get(caches.size() - 1).epoch); } } } }
10,024
35.061151
134
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/MessageRoundtrip.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.message.Message; /** * Utility wraps around a message to keep track of the number of times it has * been offered This class also contains the last time a message was offered and * is updated when an answer has been received to it can be removed from the * queue. * * @author Roman Mandeleil */ public class MessageRoundtrip { private final Message msg; long lastTimestamp = 0; long retryTimes = 0; boolean answered = false; public MessageRoundtrip(Message msg) { this.msg = msg; saveTime(); } public boolean isAnswered() { return answered; } public void answer() { answered = true; } public long getRetryTimes() { return retryTimes; } public void incRetryTimes() { ++retryTimes; } public void saveTime() { lastTimestamp = System.currentTimeMillis(); } public boolean hasToRetry() { return 20000 < System.currentTimeMillis() - lastTimestamp; } public Message getMsg() { return msg; } }
1,895
26.085714
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import org.ethereum.listener.EthereumListener; import org.ethereum.net.eth.message.EthMessage; import org.ethereum.net.message.Message; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.p2p.DisconnectMessage; import org.ethereum.net.p2p.PingMessage; import org.ethereum.net.p2p.PongMessage; import org.ethereum.net.server.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.Queue; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static org.ethereum.net.message.StaticMessages.DISCONNECT_MESSAGE; /** * This class contains the logic for sending messages in a queue * * Messages open by send and answered by receive of appropriate message * PING by PONG * GET_PEERS by PEERS * GET_TRANSACTIONS by TRANSACTIONS * GET_BLOCK_HASHES by BLOCK_HASHES * GET_BLOCKS by BLOCKS * * The following messages will not be answered: * PONG, PEERS, HELLO, STATUS, TRANSACTIONS, BLOCKS * * @author Roman Mandeleil */ @Component @Scope("prototype") public class MessageQueue { private static final Logger logger = LoggerFactory.getLogger("net"); private static final ScheduledExecutorService timer = Executors.newScheduledThreadPool(4, new ThreadFactory() { private AtomicInteger cnt = new AtomicInteger(0); public Thread newThread(Runnable r) { return new Thread(r, "MessageQueueTimer-" + cnt.getAndIncrement()); } }); private Queue<MessageRoundtrip> requestQueue = new ConcurrentLinkedQueue<>(); private Queue<MessageRoundtrip> respondQueue = new ConcurrentLinkedQueue<>(); private ChannelHandlerContext ctx = null; @Autowired EthereumListener ethereumListener; boolean hasPing = false; private ScheduledFuture<?> timerTask; private Channel channel; public MessageQueue() { } public void activate(ChannelHandlerContext ctx) { this.ctx = ctx; timerTask = timer.scheduleAtFixedRate(() -> { try { nudgeQueue(); } catch (Throwable t) { logger.error("Unhandled exception", t); } }, 10, 10, TimeUnit.MILLISECONDS); } public void setChannel(Channel channel) { this.channel = channel; } public void sendMessage(Message msg) { if (channel.isDisconnected()) { logger.warn("{}: attempt to send [{}] message after disconnect", channel, msg.getCommand().name()); return; } if (msg instanceof PingMessage) { if (hasPing) return; hasPing = true; } if (msg.getAnswerMessage() != null) requestQueue.add(new MessageRoundtrip(msg)); else respondQueue.add(new MessageRoundtrip(msg)); } public void disconnect() { disconnect(DISCONNECT_MESSAGE); } public void disconnect(ReasonCode reason) { disconnect(new DisconnectMessage(reason)); } private void disconnect(DisconnectMessage msg) { ctx.writeAndFlush(msg); ctx.close(); } public void receivedMessage(Message msg) throws InterruptedException { ethereumListener.trace("[Recv: " + msg + "]"); if (requestQueue.peek() != null) { MessageRoundtrip messageRoundtrip = requestQueue.peek(); Message waitingMessage = messageRoundtrip.getMsg(); if (waitingMessage instanceof PingMessage) hasPing = false; if (waitingMessage.getAnswerMessage() != null && msg.getClass() == waitingMessage.getAnswerMessage()) { messageRoundtrip.answer(); if (waitingMessage instanceof EthMessage) channel.getPeerStats().pong(messageRoundtrip.lastTimestamp); logger.trace("Message round trip covered: [{}] ", messageRoundtrip.getMsg().getClass()); } } } private void removeAnsweredMessage(MessageRoundtrip messageRoundtrip) { if (messageRoundtrip != null && messageRoundtrip.isAnswered()) requestQueue.remove(); } private void nudgeQueue() { // remove last answered message on the queue removeAnsweredMessage(requestQueue.peek()); // Now send the next message sendToWire(respondQueue.poll()); sendToWire(requestQueue.peek()); } private void sendToWire(MessageRoundtrip messageRoundtrip) { if (messageRoundtrip != null && messageRoundtrip.getRetryTimes() == 0) { // TODO: retry logic || messageRoundtrip.hasToRetry()){ Message msg = messageRoundtrip.getMsg(); ethereumListener.onSendMessage(channel, msg); ctx.writeAndFlush(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); if (msg.getAnswerMessage() != null) { messageRoundtrip.incRetryTimes(); messageRoundtrip.saveTime(); } } } public void close() { if (timerTask != null) { timerTask.cancel(false); } } }
6,229
32.315508
115
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/EthVersion.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth; import java.util.ArrayList; import java.util.List; /** * Represents supported Eth versions * * @author Mikhail Kalinin * @since 14.08.2015 */ public enum EthVersion { V62((byte) 62), V63((byte) 63); public static final byte LOWER = V62.getCode(); public static final byte UPPER = V63.getCode(); private byte code; EthVersion(byte code) { this.code = code; } public byte getCode() { return code; } public static EthVersion fromCode(int code) { for (EthVersion v : values()) { if (v.code == code) { return v; } } return null; } public static boolean isSupported(byte code) { return code >= LOWER && code <= UPPER; } public static List<EthVersion> supported() { List<EthVersion> supported = new ArrayList<>(); for (EthVersion v : values()) { if (isSupported(v.code)) { supported.add(v); } } return supported; } public boolean isCompatible(EthVersion version) { if (version.getCode() >= V62.getCode()) { return this.getCode() >= V62.getCode(); } else { return this.getCode() < V62.getCode(); } } }
2,109
25.049383
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/EthHandlerFactoryImpl.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import org.ethereum.net.eth.EthVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * Default factory implementation * * @author Mikhail Kalinin * @since 20.08.2015 */ @Component public class EthHandlerFactoryImpl implements EthHandlerFactory { @Autowired private ApplicationContext ctx; @Override public EthHandler create(EthVersion version) { switch (version) { case V62: return (EthHandler) ctx.getBean("Eth62"); case V63: return (EthHandler) ctx.getBean("Eth63"); default: throw new IllegalArgumentException("Eth " + version + " is not supported"); } } }
1,602
33.847826
99
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/Eth62.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.db.BlockStore; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.eth.message.*; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.rlpx.discover.NodeManager; import org.ethereum.net.submit.TransactionExecutor; import org.ethereum.net.submit.TransactionTask; import org.ethereum.sync.SyncManager; import org.ethereum.sync.PeerState; import org.ethereum.sync.SyncStatistics; import org.ethereum.util.ByteUtil; import org.ethereum.validator.BlockHeaderRule; import org.ethereum.validator.BlockHeaderValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.*; import static java.lang.Math.min; import static java.util.Collections.singletonList; import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator; import static org.ethereum.net.eth.EthVersion.V62; import static org.ethereum.net.message.ReasonCode.USELESS_PEER; import static org.ethereum.sync.PeerState.*; import static org.ethereum.sync.PeerState.BLOCK_RETRIEVING; import static org.ethereum.util.Utils.longToTimePeriod; import static org.ethereum.util.ByteUtil.toHexString; /** * Eth 62 * * @author Mikhail Kalinin * @since 04.09.2015 */ @Component("Eth62") @Scope("prototype") public class Eth62 extends EthHandler { protected static final int MAX_HASHES_TO_SEND = 1024; public static final int MAX_MESSAGE_SIZE = 32 * 1024 * 1024; protected final static Logger logger = LoggerFactory.getLogger("sync"); protected final static Logger loggerNet = LoggerFactory.getLogger("net"); @Autowired protected BlockStore blockstore; @Autowired protected SyncManager syncManager; @Autowired protected PendingState pendingState; @Autowired protected NodeManager nodeManager; protected EthState ethState = EthState.INIT; protected PeerState peerState = IDLE; protected boolean syncDone = false; /** * Number and hash of best known remote block */ protected BlockIdentifier bestKnownBlock; private BigInteger totalDifficulty; /** * Header list sent in GET_BLOCK_BODIES message, * used to create blocks from headers and bodies * also, is useful when returned BLOCK_BODIES msg doesn't cover all sent hashes * or in case when peer is disconnected */ protected final List<BlockHeaderWrapper> sentHeaders = Collections.synchronizedList(new ArrayList<BlockHeaderWrapper>()); protected SettableFuture<List<Block>> futureBlocks; protected final SyncStatistics syncStats = new SyncStatistics(); protected GetBlockHeadersMessageWrapper headerRequest; private Map<Long, BlockHeaderValidator> validatorMap; protected long lastReqSentTime; protected long connectedTime = System.currentTimeMillis(); protected long processingTime = 0; private static final EthVersion version = V62; public Eth62() { this(version); } Eth62(final EthVersion version) { super(version); } @Autowired public Eth62(final SystemProperties config, final Blockchain blockchain, final BlockStore blockStore, final CompositeEthereumListener ethereumListener) { this(version, config, blockchain, blockStore, ethereumListener); } Eth62(final EthVersion version, final SystemProperties config, final Blockchain blockchain, final BlockStore blockStore, final CompositeEthereumListener ethereumListener) { super(version, config, blockchain, blockStore, ethereumListener); } @Override public void channelRead0(final ChannelHandlerContext ctx, EthMessage msg) throws InterruptedException { super.channelRead0(ctx, msg); switch (msg.getCommand()) { case STATUS: processStatus((StatusMessage) msg, ctx); break; case NEW_BLOCK_HASHES: processNewBlockHashes((NewBlockHashesMessage) msg); break; case TRANSACTIONS: processTransactions((TransactionsMessage) msg); break; case GET_BLOCK_HEADERS: processGetBlockHeaders((GetBlockHeadersMessage) msg); break; case BLOCK_HEADERS: processBlockHeaders((BlockHeadersMessage) msg); break; case GET_BLOCK_BODIES: processGetBlockBodies((GetBlockBodiesMessage) msg); break; case BLOCK_BODIES: processBlockBodies((BlockBodiesMessage) msg); break; case NEW_BLOCK: processNewBlock((NewBlockMessage) msg); break; default: break; } } /************************* * Message Sending * *************************/ @Override public synchronized void sendStatus() { byte protocolVersion = getVersion().getCode(); int networkId = config.networkId(); final BigInteger totalDifficulty; final byte[] bestHash; if (syncManager.isFastSyncRunning()) { // while fastsync is not complete reporting block #0 // until all blocks/receipts are downloaded bestHash = blockstore.getBlockHashByNumber(0); Block genesis = blockstore.getBlockByHash(bestHash); totalDifficulty = genesis.getDifficultyBI(); } else { // Getting it from blockstore, not blocked by blockchain sync bestHash = blockstore.getBestBlock().getHash(); totalDifficulty = blockchain.getTotalDifficulty(); } StatusMessage msg = new StatusMessage(protocolVersion, networkId, ByteUtil.bigIntegerToBytes(totalDifficulty), bestHash, config.getGenesis().getHash()); sendMessage(msg); ethState = EthState.STATUS_SENT; sendNextHeaderRequest(); } @Override public synchronized void sendNewBlockHashes(Block block) { BlockIdentifier identifier = new BlockIdentifier(block.getHash(), block.getNumber()); NewBlockHashesMessage msg = new NewBlockHashesMessage(singletonList(identifier)); sendMessage(msg); } @Override public synchronized void sendTransaction(List<Transaction> txs) { TransactionsMessage msg = new TransactionsMessage(txs); sendMessage(msg); } @Override public synchronized ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(long blockNumber, int maxBlocksAsk, boolean reverse) { if (ethState == EthState.STATUS_SUCCEEDED && peerState != IDLE) return null; if(logger.isTraceEnabled()) logger.trace( "Peer {}: queue GetBlockHeaders, blockNumber [{}], maxBlocksAsk [{}]", channel.getPeerIdShort(), blockNumber, maxBlocksAsk ); if (headerRequest != null) { throw new RuntimeException("The peer is waiting for headers response: " + this); } GetBlockHeadersMessage headersRequest = new GetBlockHeadersMessage(blockNumber, null, maxBlocksAsk, 0, reverse); GetBlockHeadersMessageWrapper messageWrapper = new GetBlockHeadersMessageWrapper(headersRequest); headerRequest = messageWrapper; sendNextHeaderRequest(); return messageWrapper.getFutureHeaders(); } @Override public synchronized ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse) { return sendGetBlockHeaders(blockHash, maxBlocksAsk, skip, reverse, false); } protected synchronized void sendGetNewBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse) { sendGetBlockHeaders(blockHash, maxBlocksAsk, skip, reverse, true); } protected synchronized ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse, boolean newHashes) { if (peerState != IDLE) return null; if(logger.isTraceEnabled()) logger.trace( "Peer {}: queue GetBlockHeaders, blockHash [{}], maxBlocksAsk [{}], skip[{}], reverse [{}]", channel.getPeerIdShort(), "0x" + toHexString(blockHash).substring(0, 8), maxBlocksAsk, skip, reverse ); if (headerRequest != null) { throw new RuntimeException("The peer is waiting for headers response: " + this); } GetBlockHeadersMessage headersRequest = new GetBlockHeadersMessage(0, blockHash, maxBlocksAsk, skip, reverse); GetBlockHeadersMessageWrapper messageWrapper = new GetBlockHeadersMessageWrapper(headersRequest, newHashes); headerRequest = messageWrapper; sendNextHeaderRequest(); lastReqSentTime = System.currentTimeMillis(); return messageWrapper.getFutureHeaders(); } @Override public synchronized ListenableFuture<List<Block>> sendGetBlockBodies(List<BlockHeaderWrapper> headers) { if (peerState != IDLE) return null; peerState = BLOCK_RETRIEVING; sentHeaders.clear(); sentHeaders.addAll(headers); if(logger.isTraceEnabled()) logger.trace( "Peer {}: send GetBlockBodies, hashes.count [{}]", channel.getPeerIdShort(), sentHeaders.size() ); List<byte[]> hashes = new ArrayList<>(headers.size()); for (BlockHeaderWrapper header : headers) { hashes.add(header.getHash()); } GetBlockBodiesMessage msg = new GetBlockBodiesMessage(hashes); sendMessage(msg); lastReqSentTime = System.currentTimeMillis(); futureBlocks = SettableFuture.create(); return futureBlocks; } @Override public synchronized void sendNewBlock(Block block) { BigInteger parentTD = blockstore.getTotalDifficultyForHash(block.getParentHash()); byte[] td = ByteUtil.bigIntegerToBytes(parentTD.add(new BigInteger(1, block.getDifficulty()))); NewBlockMessage msg = new NewBlockMessage(block, td); sendMessage(msg); } /************************* * Message Processing * *************************/ protected synchronized void processStatus(StatusMessage msg, ChannelHandlerContext ctx) throws InterruptedException { try { if (!Arrays.equals(msg.getGenesisHash(), config.getGenesis().getHash())) { if (!peerDiscoveryMode) { loggerNet.debug("Removing EthHandler for {} due to protocol incompatibility", ctx.channel().remoteAddress()); } ethState = EthState.STATUS_FAILED; disconnect(ReasonCode.INCOMPATIBLE_PROTOCOL); ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol return; } if (msg.getNetworkId() != config.networkId()) { ethState = EthState.STATUS_FAILED; disconnect(ReasonCode.NULL_IDENTITY); return; } // basic checks passed, update statistics channel.getNodeStatistics().ethHandshake(msg); ethereumListener.onEthStatusUpdated(channel, msg); if (peerDiscoveryMode) { loggerNet.trace("Peer discovery mode: STATUS received, disconnecting..."); disconnect(ReasonCode.REQUESTED); ctx.close().sync(); ctx.disconnect().sync(); return; } // update bestKnownBlock info sendGetBlockHeaders(msg.getBestHash(), 1, 0, false); } catch (NoSuchElementException e) { loggerNet.debug("EthHandler already removed"); } } protected synchronized void processNewBlockHashes(NewBlockHashesMessage msg) { if(logger.isTraceEnabled()) logger.trace( "Peer {}: processing NewBlockHashes, size [{}]", channel.getPeerIdShort(), msg.getBlockIdentifiers().size() ); List<BlockIdentifier> identifiers = msg.getBlockIdentifiers(); if (identifiers.isEmpty()) return; updateBestBlock(identifiers); // queueing new blocks doesn't make sense // while Long sync is in progress if (!syncDone) return; if (peerState != HEADER_RETRIEVING) { long firstBlockAsk = Long.MAX_VALUE; long lastBlockAsk = 0; byte[] firstBlockHash = null; for (BlockIdentifier identifier : identifiers) { long blockNumber = identifier.getNumber(); if (blockNumber < firstBlockAsk) { firstBlockAsk = blockNumber; firstBlockHash = identifier.getHash(); } if (blockNumber > lastBlockAsk) { lastBlockAsk = blockNumber; } } long maxBlocksAsk = lastBlockAsk - firstBlockAsk + 1; if (firstBlockHash != null && maxBlocksAsk > 0 && maxBlocksAsk < MAX_HASHES_TO_SEND) { sendGetNewBlockHeaders(firstBlockHash, (int) maxBlocksAsk, 0, false); } } } protected synchronized void processTransactions(TransactionsMessage msg) { if(!processTransactions) { return; } List<Transaction> txSet = msg.getTransactions(); List<Transaction> newPending = pendingState.addPendingTransactions(txSet); if (!newPending.isEmpty()) { TransactionTask transactionTask = new TransactionTask(newPending, channel.getChannelManager(), channel); TransactionExecutor.instance.submitTransaction(transactionTask); } } protected synchronized void processGetBlockHeaders(GetBlockHeadersMessage msg) { Iterator<BlockHeader> headersIterator = blockchain.getIteratorOfHeadersStartFrom( msg.getBlockIdentifier(), msg.getSkipBlocks(), min(msg.getMaxHeaders(), MAX_HASHES_TO_SEND), msg.isReverse() ); List<BlockHeader> blockHeaders = new ArrayList<>(); while (headersIterator.hasNext()) { blockHeaders.add(headersIterator.next()); } BlockHeadersMessage response = new BlockHeadersMessage(blockHeaders); sendMessage(response); } protected synchronized void processBlockHeaders(BlockHeadersMessage msg) { if(logger.isTraceEnabled()) logger.trace( "Peer {}: processing BlockHeaders, size [{}]", channel.getPeerIdShort(), msg.getBlockHeaders().size() ); GetBlockHeadersMessageWrapper request = headerRequest; headerRequest = null; if (!isValid(msg, request)) { dropConnection(); return; } List<BlockHeader> received = msg.getBlockHeaders(); if (ethState == EthState.STATUS_SENT || ethState == EthState.HASH_CONSTRAINTS_CHECK) processInitHeaders(received); else { syncStats.addHeaders(received.size()); request.getFutureHeaders().set(received); } processingTime += lastReqSentTime > 0 ? (System.currentTimeMillis() - lastReqSentTime) : 0; lastReqSentTime = 0; peerState = IDLE; } protected synchronized void processGetBlockBodies(GetBlockBodiesMessage msg) { Iterator<byte[]> bodiesIterator = blockchain.getIteratorOfBodiesByHashes(msg.getBlockHashes()); List<byte[]> bodies = new ArrayList<>(); int sizeSum = 0; while (bodiesIterator.hasNext()) { byte[] body = bodiesIterator.next(); sizeSum += ByteArrayEstimator.estimateSize(body); bodies.add(body); if (sizeSum >= MAX_MESSAGE_SIZE) break; } BlockBodiesMessage response = new BlockBodiesMessage(bodies); sendMessage(response); } protected synchronized void processBlockBodies(BlockBodiesMessage msg) { if (logger.isTraceEnabled()) logger.trace( "Peer {}: process BlockBodies, size [{}]", channel.getPeerIdShort(), msg.getBlockBodies().size() ); if (!isValid(msg)) { dropConnection(); return; } syncStats.addBlocks(msg.getBlockBodies().size()); List<Block> blocks = null; try { blocks = validateAndMerge(msg); } catch (Exception e) { logger.info("Fatal validation error while processing block bodies from peer {}", channel.getPeerIdShort()); } if (blocks == null) { // headers will be returned by #onShutdown() dropConnection(); return; } futureBlocks.set(blocks); futureBlocks = null; processingTime += (System.currentTimeMillis() - lastReqSentTime); lastReqSentTime = 0; peerState = IDLE; } protected synchronized void processNewBlock(NewBlockMessage newBlockMessage) { Block newBlock = newBlockMessage.getBlock(); logger.debug("New block received: block.index [{}]", newBlock.getNumber()); updateTotalDifficulty(newBlockMessage.getDifficultyAsBigInt()); updateBestBlock(newBlock); if (!syncManager.validateAndAddNewBlock(newBlock, channel.getNodeId())) { dropConnection(); } } /************************* * Sync Management * *************************/ @Override public synchronized void onShutdown() { } @Override public synchronized void fetchBodies(List<BlockHeaderWrapper> headers) { syncStats.reset(); sendGetBlockBodies(headers); } protected synchronized void sendNextHeaderRequest() { // do not send header requests if status hasn't been passed yet if (ethState == EthState.INIT) return; GetBlockHeadersMessageWrapper wrapper = headerRequest; if (wrapper == null || wrapper.isSent()) return; peerState = HEADER_RETRIEVING; wrapper.send(); sendMessage(wrapper.getMessage()); lastReqSentTime = System.currentTimeMillis(); } protected synchronized void processInitHeaders(List<BlockHeader> received) { final BlockHeader blockHeader = received.get(0); final long blockNumber = blockHeader.getNumber(); if (ethState == EthState.STATUS_SENT) { updateBestBlock(blockHeader); logger.trace("Peer {}: init request succeeded, best known block {}", channel.getPeerIdShort(), bestKnownBlock); // checking if the peer has expected block hashes ethState = EthState.HASH_CONSTRAINTS_CHECK; validatorMap = Collections.synchronizedMap(new HashMap<Long, BlockHeaderValidator>()); List<Pair<Long, BlockHeaderValidator>> validators = config.getBlockchainConfig(). getConfigForBlock(blockNumber).headerValidators(); for (Pair<Long, BlockHeaderValidator> validator : validators) { if (validator.getLeft() <= getBestKnownBlock().getNumber()) { validatorMap.put(validator.getLeft(), validator.getRight()); } } logger.trace("Peer " + channel.getPeerIdShort() + ": Requested " + validatorMap.size() + " headers for hash check: " + validatorMap.keySet()); requestNextHashCheck(); } else { BlockHeaderValidator validator = validatorMap.get(blockNumber); if (validator != null) { BlockHeaderRule.ValidationResult result = validator.validate(blockHeader); if (result.success) { validatorMap.remove(blockNumber); requestNextHashCheck(); } else { logger.debug("Peer {}: wrong fork ({}). Drop the peer and reduce reputation.", channel.getPeerIdShort(), result.error); channel.getNodeStatistics().wrongFork = true; dropConnection(); } } } if (validatorMap.isEmpty()) { ethState = EthState.STATUS_SUCCEEDED; logger.trace("Peer {}: all validations passed", channel.getPeerIdShort()); } } private void requestNextHashCheck() { if (!validatorMap.isEmpty()) { final Long checkHeader = validatorMap.keySet().iterator().next(); sendGetBlockHeaders(checkHeader, 1, false); logger.trace("Peer {}: Requested #{} header for hash check.", channel.getPeerIdShort(), checkHeader); } } private void updateBestBlock(Block block) { updateBestBlock(block.getHeader()); } private void updateBestBlock(BlockHeader header) { if (bestKnownBlock == null || header.getNumber() > bestKnownBlock.getNumber()) { bestKnownBlock = new BlockIdentifier(header.getHash(), header.getNumber()); } } private void updateBestBlock(List<BlockIdentifier> identifiers) { for (BlockIdentifier id : identifiers) if (bestKnownBlock == null || id.getNumber() > bestKnownBlock.getNumber()) { bestKnownBlock = id; } } @Override public BlockIdentifier getBestKnownBlock() { return bestKnownBlock; } private void updateTotalDifficulty(BigInteger totalDiff) { channel.getNodeStatistics().setEthTotalDifficulty(totalDiff); this.totalDifficulty = totalDiff; } @Override public BigInteger getTotalDifficulty() { return totalDifficulty != null ? totalDifficulty : channel.getNodeStatistics().getEthTotalDifficulty(); } /************************* * Getters, setters * *************************/ @Override public boolean isHashRetrievingDone() { return peerState == DONE_HASH_RETRIEVING; } @Override public boolean isHashRetrieving() { return peerState == HEADER_RETRIEVING; } @Override public boolean hasStatusPassed() { return ethState.ordinal() > EthState.HASH_CONSTRAINTS_CHECK.ordinal(); } @Override public boolean hasStatusSucceeded() { return ethState == EthState.STATUS_SUCCEEDED; } @Override public boolean isIdle() { return peerState == IDLE; } @Override public void enableTransactions() { processTransactions = true; } @Override public void disableTransactions() { processTransactions = false; } @Override public SyncStatistics getStats() { return syncStats; } @Override public void onSyncDone(boolean done) { syncDone = done; } /************************* * Validation * *************************/ @Nullable private List<Block> validateAndMerge(BlockBodiesMessage response) { // merging received block bodies with requested headers // the assumption is the following: // - response may miss any bodies present in the request // - response may not contain non-requested bodies // - order of response bodies should be preserved // Otherwise the response is assumed invalid and all bodies are dropped List<byte[]> bodyList = response.getBlockBodies(); Iterator<byte[]> bodies = bodyList.iterator(); Iterator<BlockHeaderWrapper> wrappers = sentHeaders.iterator(); List<Block> blocks = new ArrayList<>(bodyList.size()); List<BlockHeaderWrapper> coveredHeaders = new ArrayList<>(sentHeaders.size()); boolean blockMerged = true; byte[] body = null; while (bodies.hasNext() && wrappers.hasNext()) { BlockHeaderWrapper wrapper = wrappers.next(); if (blockMerged) { body = bodies.next(); } Block b = new Block.Builder() .withHeader(wrapper.getHeader()) .withBody(body) .create(); if (b == null) { blockMerged = false; } else { blockMerged = true; coveredHeaders.add(wrapper); blocks.add(b); } } if (bodies.hasNext()) { logger.info("Peer {}: invalid BLOCK_BODIES response: at least one block body doesn't correspond to any of requested headers: ", channel.getPeerIdShort(), toHexString(bodies.next())); return null; } // remove headers covered by response sentHeaders.removeAll(coveredHeaders); return blocks; } private boolean isValid(BlockBodiesMessage response) { return response.getBlockBodies().size() <= sentHeaders.size(); } protected boolean isValid(BlockHeadersMessage response, GetBlockHeadersMessageWrapper requestWrapper) { GetBlockHeadersMessage request = requestWrapper.getMessage(); List<BlockHeader> headers = response.getBlockHeaders(); // max headers if (headers.size() > request.getMaxHeaders()) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, exceeds maxHeaders limit, headers count={}", channel.getPeerIdShort(), request, headers.size() ); return false; } // emptiness against best known block if (headers.isEmpty()) { // initial call after handshake if (ethState == EthState.STATUS_SENT || ethState == EthState.HASH_CONSTRAINTS_CHECK) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to initial {}, empty", channel.getPeerIdShort(), request ); return false; } if (request.getBlockHash() == null && request.getBlockNumber() <= bestKnownBlock.getNumber()) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, it's empty while bestKnownBlock is {}", channel.getPeerIdShort(), request, bestKnownBlock ); return false; } return true; } // first header BlockHeader first = headers.get(0); if (request.getBlockHash() != null) { if (!Arrays.equals(request.getBlockHash(), first.getHash())) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, first header is invalid {}", channel.getPeerIdShort(), request, first ); return false; } } else { if (request.getBlockNumber() != first.getNumber()) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, first header is invalid {}", channel.getPeerIdShort(), request, first ); return false; } } // skip following checks in case of NEW_BLOCK_HASHES handling if (requestWrapper.isNewHashesHandling()) return true; // numbers and ancestors int offset = 1 + request.getSkipBlocks(); if (request.isReverse()) offset = -offset; for (int i = 1; i < headers.size(); i++) { BlockHeader cur = headers.get(i); BlockHeader prev = headers.get(i - 1); long num = cur.getNumber(); long expectedNum = prev.getNumber() + offset; if (num != expectedNum) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, got #{}, expected #{}", channel.getPeerIdShort(), request, num, expectedNum ); return false; } if (request.getSkipBlocks() == 0) { BlockHeader parent; BlockHeader child; if (request.isReverse()) { parent = cur; child = prev; } else { parent = prev; child = cur; } if (!Arrays.equals(child.getParentHash(), parent.getHash())) { if (logger.isInfoEnabled()) logger.info( "Peer {}: invalid response to {}, got parent hash {} for #{}, expected {}", channel.getPeerIdShort(), request, toHexString(child.getParentHash()), prev.getNumber(), toHexString(parent.getHash()) ); return false; } } } return true; } @Override public synchronized void dropConnection() { logger.info("Peer {}: is a bad one, drop", channel.getPeerIdShort()); disconnect(USELESS_PEER); } /************************* * Logging * *************************/ @Override public String getSyncStats() { int waitResp = lastReqSentTime > 0 ? (int) (System.currentTimeMillis() - lastReqSentTime) / 1000 : 0; long lifeTime = System.currentTimeMillis() - connectedTime; return String.format( "Peer %s: [ %s, %18s, ping %6s ms, rep: %s, difficulty %s, best block %s%s]: (idle %s of %s) %s", getVersion(), channel.getPeerIdShort(), peerState, (int)channel.getPeerStats().getAvgLatency(), channel.getNodeStatistics().getReputation(), getTotalDifficulty(), getBestKnownBlock().getNumber(), waitResp > 5 ? ", wait " + waitResp + "s" : " ", longToTimePeriod(lifeTime - processingTime), longToTimePeriod(lifeTime), channel.getNodeStatistics().getClientId()); } protected enum EthState { INIT, STATUS_SENT, HASH_CONSTRAINTS_CHECK, STATUS_SUCCEEDED, STATUS_FAILED } }
31,890
34.316722
166
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/Eth63.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.datasource.Source; import org.ethereum.db.BlockStore; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.eth.message.EthMessage; import org.ethereum.net.eth.message.GetNodeDataMessage; import org.ethereum.net.eth.message.GetReceiptsMessage; import org.ethereum.net.eth.message.NodeDataMessage; import org.ethereum.net.eth.message.ReceiptsMessage; import org.ethereum.net.message.ReasonCode; import org.ethereum.sync.PeerState; import org.ethereum.util.ByteArraySet; import org.ethereum.util.Value; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Set; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.net.eth.EthVersion.V63; import static org.ethereum.util.ByteUtil.toHexString; /** * Fast synchronization (PV63) Handler */ @Component("Eth63") @Scope("prototype") public class Eth63 extends Eth62 { private static final EthVersion version = V63; @Autowired @Qualifier("trieNodeSource") private Source<byte[], byte[]> trieNodeSource; private List<byte[]> requestedReceipts; private SettableFuture<List<List<TransactionReceipt>>> requestReceiptsFuture; private Set<byte[]> requestedNodes; private SettableFuture<List<Pair<byte[], byte[]>>> requestNodesFuture; public Eth63() { super(version); } @Autowired public Eth63(final SystemProperties config, final Blockchain blockchain, BlockStore blockStore, final CompositeEthereumListener ethereumListener) { super(version, config, blockchain, blockStore, ethereumListener); } @Override public void channelRead0(final ChannelHandlerContext ctx, EthMessage msg) throws InterruptedException { super.channelRead0(ctx, msg); // Only commands that were added in V63, V62 are handled in child switch (msg.getCommand()) { case GET_NODE_DATA: processGetNodeData((GetNodeDataMessage) msg); break; case NODE_DATA: processNodeData((NodeDataMessage) msg); break; case GET_RECEIPTS: processGetReceipts((GetReceiptsMessage) msg); break; case RECEIPTS: processReceipts((ReceiptsMessage) msg); break; default: break; } } protected synchronized void processGetNodeData(GetNodeDataMessage msg) { if (logger.isTraceEnabled()) logger.trace( "Peer {}: processing GetNodeData, size [{}]", channel.getPeerIdShort(), msg.getNodeKeys().size() ); List<Value> nodeValues = new ArrayList<>(); for (byte[] nodeKey : msg.getNodeKeys()) { byte[] rawNode = trieNodeSource.get(nodeKey); if (rawNode != null) { Value value = new Value(rawNode); nodeValues.add(value); if (nodeValues.size() >= MAX_HASHES_TO_SEND) break; logger.trace("Eth63: " + toHexString(nodeKey).substring(0, 8) + " -> " + value); } } sendMessage(new NodeDataMessage(nodeValues)); } protected synchronized void processGetReceipts(GetReceiptsMessage msg) { if (logger.isTraceEnabled()) logger.trace( "Peer {}: processing GetReceipts, size [{}]", channel.getPeerIdShort(), msg.getBlockHashes().size() ); List<List<TransactionReceipt>> receipts = new ArrayList<>(); int sizeSum = 0; for (byte[] blockHash : msg.getBlockHashes()) { Block block = blockchain.getBlockByHash(blockHash); if (block == null) continue; List<TransactionReceipt> blockReceipts = new ArrayList<>(); for (Transaction transaction : block.getTransactionsList()) { TransactionInfo transactionInfo = blockchain.getTransactionInfo(transaction.getHash()); if (transactionInfo == null) break; blockReceipts.add(transactionInfo.getReceipt()); sizeSum += TransactionReceipt.MemEstimator.estimateSize(transactionInfo.getReceipt()); } receipts.add(blockReceipts); if (sizeSum >= MAX_MESSAGE_SIZE) break; } sendMessage(new ReceiptsMessage(receipts)); } public synchronized ListenableFuture<List<Pair<byte[], byte[]>>> requestTrieNodes(List<byte[]> hashes) { if (peerState != PeerState.IDLE) return null; GetNodeDataMessage msg = new GetNodeDataMessage(hashes); requestedNodes = new ByteArraySet(); requestedNodes.addAll(hashes); requestNodesFuture = SettableFuture.create(); sendMessage(msg); lastReqSentTime = System.currentTimeMillis(); peerState = PeerState.NODE_RETRIEVING; return requestNodesFuture; } public synchronized ListenableFuture<List<List<TransactionReceipt>>> requestReceipts(List<byte[]> hashes) { if (peerState != PeerState.IDLE) return null; GetReceiptsMessage msg = new GetReceiptsMessage(hashes); requestedReceipts = hashes; peerState = PeerState.RECEIPT_RETRIEVING; requestReceiptsFuture = SettableFuture.create(); sendMessage(msg); lastReqSentTime = System.currentTimeMillis(); return requestReceiptsFuture; } protected synchronized void processNodeData(NodeDataMessage msg) { if (requestedNodes == null) { logger.debug("Received NodeDataMessage when requestedNodes == null. Dropping peer " + channel); dropConnection(); } List<Pair<byte[], byte[]>> ret = new ArrayList<>(); if(msg.getDataList().isEmpty()) { String err = String.format("Received NodeDataMessage contains empty node data. Dropping peer %s", channel); logger.debug(err); requestNodesFuture.setException(new RuntimeException(err)); // Not fatal but let us touch it later channel.getChannelManager().disconnect(channel, ReasonCode.TOO_MANY_PEERS); return; } for (Value nodeVal : msg.getDataList()) { byte[] hash = sha3(nodeVal.asBytes()); if (!requestedNodes.contains(hash)) { String err = "Received NodeDataMessage contains non-requested node with hash :" + toHexString(hash) + " . Dropping peer " + channel; dropUselessPeer(err); return; } ret.add(Pair.of(hash, nodeVal.asBytes())); } requestNodesFuture.set(ret); requestedNodes = null; requestNodesFuture = null; processingTime += (System.currentTimeMillis() - lastReqSentTime); lastReqSentTime = 0; peerState = PeerState.IDLE; } protected synchronized void processReceipts(ReceiptsMessage msg) { if (requestedReceipts == null) { logger.debug("Received ReceiptsMessage when requestedReceipts == null. Dropping peer " + channel); dropConnection(); } if (logger.isTraceEnabled()) logger.trace( "Peer {}: processing Receipts, size [{}]", channel.getPeerIdShort(), msg.getReceipts().size() ); List<List<TransactionReceipt>> receipts = msg.getReceipts(); requestReceiptsFuture.set(receipts); requestedReceipts = null; requestReceiptsFuture = null; processingTime += (System.currentTimeMillis() - lastReqSentTime); lastReqSentTime = 0; peerState = PeerState.IDLE; } private void dropUselessPeer(String err) { logger.debug(err); requestNodesFuture.setException(new RuntimeException(err)); dropConnection(); } @Override public String getSyncStats() { double nodesPerSec = 1000d * channel.getNodeStatistics().eth63NodesReceived.get() / channel.getNodeStatistics().eth63NodesRetrieveTime.get(); double missNodesRatio = 1 - (double) channel.getNodeStatistics().eth63NodesReceived.get() / channel.getNodeStatistics().eth63NodesRequested.get(); long lifeTime = System.currentTimeMillis() - connectedTime; return super.getSyncStats() + String.format("\tNodes/sec: %1$.2f, miss: %2$.2f", nodesPerSec, missNodesRatio); } }
9,791
37.25
154
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/Eth.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import com.google.common.util.concurrent.ListenableFuture; import org.ethereum.core.*; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.eth.message.EthMessageCodes; import org.ethereum.sync.PeerState; import org.ethereum.sync.SyncStatistics; import java.math.BigInteger; import java.util.List; /** * Describes interface required by Eth peer clients * * @see org.ethereum.net.server.Channel * * @author Mikhail Kalinin * @since 20.08.2015 */ public interface Eth { /** * @return true if StatusMessage was processed, false otherwise */ boolean hasStatusPassed(); /** * @return true if Status has succeeded */ boolean hasStatusSucceeded(); /** * Executes cleanups required to be done * during shutdown, e.g. disconnect */ void onShutdown(); /** * Puts sync statistics to log output */ String getSyncStats(); BlockIdentifier getBestKnownBlock(); BigInteger getTotalDifficulty(); /** * @return true if syncState is DONE_HASH_RETRIEVING, false otherwise */ boolean isHashRetrievingDone(); /** * @return true if syncState is HEADER_RETRIEVING, false otherwise */ boolean isHashRetrieving(); /** * @return true if syncState is IDLE, false otherwise */ boolean isIdle(); /** * @return sync statistics */ SyncStatistics getStats(); /** * Disables pending transaction processing */ void disableTransactions(); /** * Enables pending transaction processing */ void enableTransactions(); /** * Sends transaction to the wire * * @param tx sending transaction */ void sendTransaction(List<Transaction> tx); /** * Send GET_BLOCK_HEADERS message to the peer */ ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(long blockNumber, int maxBlocksAsk, boolean reverse); ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse); /** * Send GET_BLOCK_BODIES message to the peer */ ListenableFuture<List<Block>> sendGetBlockBodies(List<BlockHeaderWrapper> headers); /** * Sends new block to the wire */ void sendNewBlock(Block newBlock); /** * Sends new block hashes message to the wire */ void sendNewBlockHashes(Block block); /** * @return protocol version */ EthVersion getVersion(); /** * Fires inner logic related to long sync done or undone event * * @param done true notifies that long sync is finished, * false notifies that it's enabled again */ void onSyncDone(boolean done); /** * Sends {@link EthMessageCodes#STATUS} message */ void sendStatus(); /** * Drops connection with remote peer. * It should be called when peer don't behave */ void dropConnection(); /** * Force peer to fetch block bodies * * @param headers related headers */ void fetchBodies(List<BlockHeaderWrapper> headers); }
3,952
24.339744
123
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/EthHandler.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.ethereum.db.BlockStore; import org.ethereum.listener.EthereumListener; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.MessageQueue; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.eth.message.*; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.server.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Process the messages between peers with 'eth' capability on the network<br> * Contains common logic to all supported versions * delegating version specific stuff to its descendants * */ public abstract class EthHandler extends SimpleChannelInboundHandler<EthMessage> implements Eth { private final static Logger logger = LoggerFactory.getLogger("net"); protected Blockchain blockchain; protected SystemProperties config; protected CompositeEthereumListener ethereumListener; protected Channel channel; private MessageQueue msgQueue = null; protected EthVersion version; protected boolean peerDiscoveryMode = false; protected Block bestBlock; protected EthereumListener listener = new EthereumListenerAdapter() { @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { bestBlock = block; } }; protected boolean processTransactions = false; protected EthHandler(EthVersion version) { this.version = version; } protected EthHandler(final EthVersion version, final SystemProperties config, final Blockchain blockchain, final BlockStore blockStore, final CompositeEthereumListener ethereumListener) { this.version = version; this.config = config; this.ethereumListener = ethereumListener; this.blockchain = blockchain; bestBlock = blockStore.getBestBlock(); this.ethereumListener.addListener(listener); // when sync enabled we delay transactions processing until sync is complete processTransactions = !config.isSyncEnabled(); } @Override public void channelRead0(final ChannelHandlerContext ctx, EthMessage msg) throws InterruptedException { if (EthMessageCodes.inRange(msg.getCommand().asByte(), version)) logger.trace("EthHandler invoke: [{}]", msg.getCommand()); ethereumListener.trace(String.format("EthHandler invoke: [%s]", msg.getCommand())); channel.getNodeStatistics().ethInbound.add(); msgQueue.receivedMessage(msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn("Eth handling failed", cause); ctx.close(); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { logger.debug("handlerRemoved: kill timers in EthHandler"); ethereumListener.removeListener(listener); onShutdown(); } public void activate() { logger.debug("ETH protocol activated"); ethereumListener.trace("ETH protocol activated"); sendStatus(); } protected void disconnect(ReasonCode reason) { msgQueue.disconnect(reason); channel.getNodeStatistics().nodeDisconnectedLocal(reason); } protected void sendMessage(EthMessage message) { msgQueue.sendMessage(message); channel.getNodeStatistics().ethOutbound.add(); } public StatusMessage getHandshakeStatusMessage() { return channel.getNodeStatistics().getEthLastInboundStatusMsg(); } public void setMsgQueue(MessageQueue msgQueue) { this.msgQueue = msgQueue; } public void setPeerDiscoveryMode(boolean peerDiscoveryMode) { this.peerDiscoveryMode = peerDiscoveryMode; } public void setChannel(Channel channel) { this.channel = channel; } @Override public EthVersion getVersion() { return version; } }
5,061
32.302632
107
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/EthHandlerFactory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import org.ethereum.net.eth.EthVersion; /** * @author Mikhail Kalinin * @since 20.08.2015 */ public interface EthHandlerFactory { /** * Creates EthHandler by requested Eth version * * @param version Eth version * @return created handler * * @throws IllegalArgumentException if provided Eth version is not supported */ EthHandler create(EthVersion version); }
1,237
30.74359
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/EthAdapter.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import com.google.common.util.concurrent.ListenableFuture; import org.ethereum.core.*; import org.ethereum.net.eth.EthVersion; import org.ethereum.sync.SyncStatistics; import java.math.BigInteger; import java.util.List; import static org.ethereum.net.eth.EthVersion.*; /** * It's quite annoying to always check {@code if (eth != null)} before accessing it. <br> * * This adapter helps to avoid such checks. It provides meaningful answers to Eth client * assuming that Eth hasn't been initialized yet. <br> * * Check {@link org.ethereum.net.server.Channel} for example. * * @author Mikhail Kalinin * @since 20.08.2015 */ public class EthAdapter implements Eth { private final SyncStatistics syncStats = new SyncStatistics(); @Override public boolean hasStatusPassed() { return false; } @Override public boolean hasStatusSucceeded() { return false; } @Override public void onShutdown() { } @Override public String getSyncStats() { return ""; } @Override public boolean isHashRetrievingDone() { return false; } @Override public boolean isHashRetrieving() { return false; } @Override public boolean isIdle() { return true; } @Override public SyncStatistics getStats() { return syncStats; } @Override public void disableTransactions() { } @Override public void enableTransactions() { } @Override public void sendTransaction(List<Transaction> tx) { } @Override public ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(long blockNumber, int maxBlocksAsk, boolean reverse) { return null; } @Override public ListenableFuture<List<BlockHeader>> sendGetBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse) { return null; } @Override public ListenableFuture<List<Block>> sendGetBlockBodies(List<BlockHeaderWrapper> headers) { return null; } @Override public void sendNewBlock(Block newBlock) { } @Override public void sendNewBlockHashes(Block block) { } @Override public EthVersion getVersion() { return fromCode(UPPER); } @Override public void onSyncDone(boolean done) { } @Override public void sendStatus() { } @Override public void dropConnection() { } @Override public void fetchBodies(List<BlockHeaderWrapper> headers) { } @Override public BlockIdentifier getBestKnownBlock() { return null; } @Override public BigInteger getTotalDifficulty() { return BigInteger.ZERO; } }
3,546
22.335526
131
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/handler/GetBlockHeadersMessageWrapper.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import com.google.common.util.concurrent.SettableFuture; import org.ethereum.core.BlockHeader; import org.ethereum.net.eth.message.GetBlockHeadersMessage; import java.util.List; /** * Wraps {@link GetBlockHeadersMessage}, * adds some additional info required by get headers queue * * @author Mikhail Kalinin * @since 16.02.2016 */ public class GetBlockHeadersMessageWrapper { private GetBlockHeadersMessage message; private boolean newHashesHandling = false; private boolean sent = false; private SettableFuture<List<BlockHeader>> futureHeaders = SettableFuture.create(); public GetBlockHeadersMessageWrapper(GetBlockHeadersMessage message) { this.message = message; } public GetBlockHeadersMessageWrapper(GetBlockHeadersMessage message, boolean newHashesHandling) { this.message = message; this.newHashesHandling = newHashesHandling; } public GetBlockHeadersMessage getMessage() { return message; } public boolean isNewHashesHandling() { return newHashesHandling; } public boolean isSent() { return sent; } public void send() { this.sent = true; } public SettableFuture<List<BlockHeader>> getFutureHeaders() { return futureHeaders; } }
2,118
29.710145
101
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/BlockHeadersMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.BlockHeader; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum BlockHeaders message on the network * * @see EthMessageCodes#BLOCK_HEADERS * * @author Mikhail Kalinin * @since 04.09.2015 */ public class BlockHeadersMessage extends EthMessage { /** * List of block headers from the peer */ private List<BlockHeader> blockHeaders; public BlockHeadersMessage(byte[] encoded) { super(encoded); } public BlockHeadersMessage(List<BlockHeader> headers) { this.blockHeaders = headers; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); blockHeaders = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { RLPList rlpData = ((RLPList) paramsList.get(i)); blockHeaders.add(new BlockHeader(rlpData)); } parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (BlockHeader blockHeader : blockHeaders) encodedElements.add(blockHeader.getEncoded()); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<?> getAnswerMessage() { return null; } public List<BlockHeader> getBlockHeaders() { parse(); return blockHeaders; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.BLOCK_HEADERS; } @Override public String toString() { parse(); StringBuilder payload = new StringBuilder(); payload.append("count( ").append(blockHeaders.size()).append(" )"); if (logger.isTraceEnabled()) { payload.append(" "); for (BlockHeader header : blockHeaders) { payload.append(toHexString(header.getHash()).substring(0, 6)).append(" | "); } if (!blockHeaders.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } else { if (blockHeaders.size() > 0) { payload.append("#").append(blockHeaders.get(0).getNumber()).append(" (") .append(toHexString(blockHeaders.get(0).getHash()).substring(0, 8)).append(")"); } if (blockHeaders.size() > 1) { payload.append(" ... #").append(blockHeaders.get(blockHeaders.size() - 1).getNumber()).append(" (") .append(toHexString(blockHeaders.get(blockHeaders.size() - 1).getHash()).substring(0, 8)).append(")"); } } return "[" + getCommand().name() + " " + payload + "]"; } }
3,972
30.531746
126
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/GetBlockBodiesMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.ethereum.util.Utils; import java.util.ArrayList; import java.util.List; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum GetBlockBodies message on the network * * @see EthMessageCodes#GET_BLOCK_BODIES * * @author Mikhail Kalinin * @since 04.09.2015 */ public class GetBlockBodiesMessage extends EthMessage { /** * List of block hashes for which to retrieve the block bodies */ private List<byte[]> blockHashes; public GetBlockBodiesMessage(byte[] encoded) { super(encoded); } public GetBlockBodiesMessage(List<byte[]> blockHashes) { this.blockHashes = blockHashes; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); blockHashes = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { blockHashes.add(paramsList.get(i).getRLPData()); } parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (byte[] hash : blockHashes) encodedElements.add(RLP.encodeElement(hash)); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<BlockBodiesMessage> getAnswerMessage() { return BlockBodiesMessage.class; } public List<byte[]> getBlockHashes() { parse(); return blockHashes; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.GET_BLOCK_BODIES; } public String toString() { parse(); StringBuilder payload = new StringBuilder(); payload.append("count( ").append(blockHashes.size()).append(" ) "); if (logger.isDebugEnabled()) { for (byte[] hash : blockHashes) { payload.append(toHexString(hash).substring(0, 6)).append(" | "); } if (!blockHashes.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } else { payload.append(Utils.getHashListShort(blockHashes)); } return "[" + getCommand().name() + " " + payload + "]"; } }
3,378
28.382609
99
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/ReceiptsMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.Bloom; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionReceipt; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPItem; import org.ethereum.util.RLPList; import org.ethereum.vm.LogInfo; import java.util.ArrayList; import java.util.List; /** * Wrapper around an Ethereum Receipts message on the network * Tx Receipts grouped by blocks * * @see EthMessageCodes#RECEIPTS */ public class ReceiptsMessage extends EthMessage { private List<List<TransactionReceipt>> receipts; public ReceiptsMessage(byte[] encoded) { super(encoded); } public ReceiptsMessage(List<List<TransactionReceipt>> receiptList) { this.receipts = receiptList; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); this.receipts = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { RLPList blockRLP = (RLPList) paramsList.get(i); List<TransactionReceipt> blockReceipts = new ArrayList<>(); for (RLPElement txReceipt : blockRLP) { RLPList receiptRLP = (RLPList) txReceipt; if (receiptRLP.size() != 4) { continue; } TransactionReceipt receipt = new TransactionReceipt(receiptRLP); blockReceipts.add(receipt); } this.receipts.add(blockReceipts); } this.parsed = true; } private void encode() { List<byte[]> blocks = new ArrayList<>(); for (List<TransactionReceipt> blockReceipts : receipts) { List<byte[]> encodedBlockReceipts = new ArrayList<>(); for (TransactionReceipt txReceipt : blockReceipts) { encodedBlockReceipts.add(txReceipt.getEncoded(true)); } byte[][] encodedElementArray = encodedBlockReceipts.toArray(new byte[encodedBlockReceipts.size()][]); byte[] blockReceiptsEncoded = RLP.encodeList(encodedElementArray); blocks.add(blockReceiptsEncoded); } byte[][] encodedElementArray = blocks.toArray(new byte[blocks.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public List<List<TransactionReceipt>> getReceipts() { parse(); return receipts; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.RECEIPTS; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { parse(); final StringBuilder sb = new StringBuilder(); if (receipts.size() < 4) { for (List<TransactionReceipt> blockReceipts : receipts) sb.append("\n ").append(blockReceipts.size()).append(" receipts in block"); } else { for (int i = 0; i < 3; i++) { sb.append("\n ").append(receipts.get(i).size()).append(" receipts in block"); } sb.append("\n ").append("[Skipped ").append(receipts.size() - 3).append(" blocks]"); } return "[" + getCommand().name() + " num:" + receipts.size() + " " + sb.toString() + "]"; } }
4,296
32.310078
113
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/GetReceiptsMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.ethereum.util.Utils; import java.util.ArrayList; import java.util.List; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum GetReceipts message on the network * * @see EthMessageCodes#GET_RECEIPTS */ public class GetReceiptsMessage extends EthMessage { /** * List of receipt hashes for which to retrieve the receipts */ private List<byte[]> blockHashes; public GetReceiptsMessage(byte[] encoded) { super(encoded); } public GetReceiptsMessage(List<byte[]> blockHashes) { this.blockHashes = blockHashes; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); this.blockHashes = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { this.blockHashes.add(paramsList.get(i).getRLPData()); } this.parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (byte[] hash : blockHashes) encodedElements.add(RLP.encodeElement(hash)); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<ReceiptsMessage> getAnswerMessage() { return ReceiptsMessage.class; } public List<byte[]> getBlockHashes() { parse(); return blockHashes; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.GET_RECEIPTS; } public String toString() { parse(); StringBuilder payload = new StringBuilder(); payload.append("count( ").append(blockHashes.size()).append(" ) "); if (logger.isDebugEnabled()) { for (byte[] hash : blockHashes) { payload.append(toHexString(hash).substring(0, 6)).append(" | "); } if (!blockHashes.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } else { payload.append(Utils.getHashListShort(blockHashes)); } return "[" + getCommand().name() + " " + payload + "]"; } }
3,317
27.852174
99
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/StatusMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.math.BigInteger; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper for Ethereum STATUS message. <br> * * @see EthMessageCodes#STATUS */ public class StatusMessage extends EthMessage { protected byte protocolVersion; protected int networkId; /** * Total difficulty of the best chain as found in block header. */ protected byte[] totalDifficulty; /** * The hash of the best (i.e. highest TD) known block. */ protected byte[] bestHash; /** * The hash of the Genesis block */ protected byte[] genesisHash; public StatusMessage(byte[] encoded) { super(encoded); } public StatusMessage(byte protocolVersion, int networkId, byte[] totalDifficulty, byte[] bestHash, byte[] genesisHash) { this.protocolVersion = protocolVersion; this.networkId = networkId; this.totalDifficulty = totalDifficulty; this.bestHash = bestHash; this.genesisHash = genesisHash; this.parsed = true; } protected synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); this.protocolVersion = paramsList.get(0).getRLPData()[0]; byte[] networkIdBytes = paramsList.get(1).getRLPData(); this.networkId = networkIdBytes == null ? 0 : ByteUtil.byteArrayToInt(networkIdBytes); byte[] diff = paramsList.get(2).getRLPData(); this.totalDifficulty = (diff == null) ? ByteUtil.ZERO_BYTE_ARRAY : diff; this.bestHash = paramsList.get(3).getRLPData(); this.genesisHash = paramsList.get(4).getRLPData(); parsed = true; } protected void encode() { byte[] protocolVersion = RLP.encodeByte(this.protocolVersion); byte[] networkId = RLP.encodeInt(this.networkId); byte[] totalDifficulty = RLP.encodeElement(this.totalDifficulty); byte[] bestHash = RLP.encodeElement(this.bestHash); byte[] genesisHash = RLP.encodeElement(this.genesisHash); this.encoded = RLP.encodeList( protocolVersion, networkId, totalDifficulty, bestHash, genesisHash); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<?> getAnswerMessage() { return null; } public byte getProtocolVersion() { parse(); return protocolVersion; } public int getNetworkId() { parse(); return networkId; } public byte[] getTotalDifficulty() { parse(); return totalDifficulty; } public BigInteger getTotalDifficultyAsBigInt() { return new BigInteger(1, getTotalDifficulty()); } public byte[] getBestHash() { parse(); return bestHash; } public byte[] getGenesisHash() { parse(); return genesisHash; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.STATUS; } @Override public String toString() { parse(); return "[" + this.getCommand().name() + " protocolVersion=" + this.protocolVersion + " networkId=" + this.networkId + " totalDifficulty=" + ByteUtil.toHexString(this.totalDifficulty) + " bestHash=" + toHexString(this.bestHash) + " genesisHash=" + toHexString(this.genesisHash) + "]"; } }
4,457
28.72
94
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/TransactionsMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.Transaction; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; import java.util.ArrayList; import java.util.List; /** * Wrapper around an Ethereum Transactions message on the network * * @see EthMessageCodes#TRANSACTIONS */ public class TransactionsMessage extends EthMessage { private List<Transaction> transactions; public TransactionsMessage(byte[] encoded) { super(encoded); } public TransactionsMessage(Transaction transaction) { transactions = new ArrayList<>(); transactions.add(transaction); parsed = true; } public TransactionsMessage(List<Transaction> transactionList) { this.transactions = transactionList; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = RLP.unwrapList(encoded); transactions = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { RLPElement rlpTxData = paramsList.get(i); Transaction tx = new Transaction(rlpTxData.getRLPData()); transactions.add(tx); } parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (Transaction tx : transactions) encodedElements.add(tx.getEncoded()); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public List<Transaction> getTransactions() { parse(); return transactions; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.TRANSACTIONS; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { parse(); final StringBuilder sb = new StringBuilder(); if (transactions.size() < 4) { for (Transaction transaction : transactions) sb.append("\n ").append(transaction.toString(128)); } else { for (int i = 0; i < 3; i++) { sb.append("\n ").append(transactions.get(i).toString(128)); } sb.append("\n ").append("[Skipped ").append(transactions.size() - 3).append(" transactions]"); } return "[" + getCommand().name() + " num:" + transactions.size() + " " + sb.toString() + "]"; } }
3,466
30.234234
108
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/Eth63MessageFactory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.net.message.Message; import org.ethereum.net.message.MessageFactory; import static org.ethereum.net.eth.EthVersion.V63; /** * Fast synchronization (PV63) message factory */ public class Eth63MessageFactory implements MessageFactory { @Override public Message create(byte code, byte[] encoded) { EthMessageCodes receivedCommand = EthMessageCodes.fromByte(code, V63); switch (receivedCommand) { case STATUS: return new StatusMessage(encoded); case NEW_BLOCK_HASHES: return new NewBlockHashesMessage(encoded); case TRANSACTIONS: return new TransactionsMessage(encoded); case GET_BLOCK_HEADERS: return new GetBlockHeadersMessage(encoded); case BLOCK_HEADERS: return new BlockHeadersMessage(encoded); case GET_BLOCK_BODIES: return new GetBlockBodiesMessage(encoded); case BLOCK_BODIES: return new BlockBodiesMessage(encoded); case NEW_BLOCK: return new NewBlockMessage(encoded); case GET_NODE_DATA: return new GetNodeDataMessage(encoded); case NODE_DATA: return new NodeDataMessage(encoded); case GET_RECEIPTS: return new GetReceiptsMessage(encoded); case RECEIPTS: return new ReceiptsMessage(encoded); default: throw new IllegalArgumentException("No such message"); } } }
2,423
36.875
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/Eth62MessageFactory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.net.message.Message; import org.ethereum.net.message.MessageFactory; import static org.ethereum.net.eth.EthVersion.V62; /** * @author Mikhail Kalinin * @since 04.09.2015 */ public class Eth62MessageFactory implements MessageFactory { @Override public Message create(byte code, byte[] encoded) { EthMessageCodes receivedCommand = EthMessageCodes.fromByte(code, V62); switch (receivedCommand) { case STATUS: return new StatusMessage(encoded); case NEW_BLOCK_HASHES: return new NewBlockHashesMessage(encoded); case TRANSACTIONS: return new TransactionsMessage(encoded); case GET_BLOCK_HEADERS: return new GetBlockHeadersMessage(encoded); case BLOCK_HEADERS: return new BlockHeadersMessage(encoded); case GET_BLOCK_BODIES: return new GetBlockBodiesMessage(encoded); case BLOCK_BODIES: return new BlockBodiesMessage(encoded); case NEW_BLOCK: return new NewBlockMessage(encoded); default: throw new IllegalArgumentException("No such message"); } } }
2,088
35.649123
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/EthMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.net.message.Message; public abstract class EthMessage extends Message { public EthMessage() { } public EthMessage(byte[] encoded) { super(encoded); } abstract public EthMessageCodes getCommand(); }
1,079
31.727273
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/EthMessageCodes.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.net.eth.EthVersion; import java.util.HashMap; import java.util.Map; import static org.ethereum.net.eth.EthVersion.*; /** * A list of commands for the Ethereum network protocol. * <br> * The codes for these commands are the first byte in every packet. * * @see <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Wire-Protocol"> * https://github.com/ethereum/wiki/wiki/Ethereum-Wire-Protocol</a> */ public enum EthMessageCodes { /* Ethereum protocol */ /** * {@code [0x00, [PROTOCOL_VERSION, NETWORK_ID, TD, BEST_HASH, GENESIS_HASH] } <br> * * Inform a peer of it's current ethereum state. This message should be * send after the initial handshake and prior to any ethereum related messages. */ STATUS(0x00), /** * PV 61 and lower <br> * {@code [+0x01, [hash_0: B_32, hash_1: B_32, ...] } <br> * * PV 62 and upper <br> * {@code [+0x01: P, [hash_0: B_32, number_0: P], [hash_1: B_32, number_1: P], ...] } <br> * * Specify one or more new blocks which have appeared on the network. * To be maximally helpful, nodes should inform peers of all blocks that they may not be aware of. * Including hashes that the sending peer could reasonably be considered to know * (due to the fact they were previously informed of because * that node has itself advertised knowledge of the hashes through NewBlockHashes) * is considered Bad Form, and may reduce the reputation of the sending node. * Including hashes that the sending node later refuses to honour with a proceeding * GetBlocks message is considered Bad Form, and may reduce the reputation of the sending node. * */ NEW_BLOCK_HASHES(0x01), /** * {@code [+0x02, [nonce, receiving_address, value, ...], ...] } <br> * * Specify (a) transaction(s) that the peer should make sure is included * on its transaction queue. The items in the list (following the first item 0x12) * are transactions in the format described in the main Ethereum specification. */ TRANSACTIONS(0x02), /** * {@code [+0x03: P, block: { P , B_32 }, maxHeaders: P, skip: P, reverse: P in { 0 , 1 } ] } <br> * * Replaces GetBlockHashes since PV 62. <br> * * Require peer to return a BlockHeaders message. * Reply must contain a number of block headers, * of rising number when reverse is 0, falling when 1, skip blocks apart, * beginning at block block (denoted by either number or hash) in the canonical chain, * and with at most maxHeaders items. */ GET_BLOCK_HEADERS(0x03), /** * {@code [+0x04, blockHeader_0, blockHeader_1, ...] } <br> * * Replaces BLOCK_HASHES since PV 62. <br> * * Reply to GetBlockHeaders. * The items in the list (following the message ID) are * block headers in the format described in the main Ethereum specification, * previously asked for in a GetBlockHeaders message. * This may validly contain no block headers * if no block headers were able to be returned for the GetBlockHeaders query. */ BLOCK_HEADERS(0x04), /** * {@code [+0x05, hash_0: B_32, hash_1: B_32, ...] } <br> * * Replaces GetBlocks since PV 62. <br> * * Require peer to return a BlockBodies message. * Specify the set of blocks that we're interested in with the hashes. */ GET_BLOCK_BODIES(0x05), /** * {@code [+0x06, [transactions_0, uncles_0] , ...] } <br> * * Replaces Blocks since PV 62. <br> * * Reply to GetBlockBodies. * The items in the list (following the message ID) are some of the blocks, minus the header, * in the format described in the main Ethereum specification, previously asked for in a GetBlockBodies message. * This may validly contain no block headers * if no block headers were able to be returned for the GetBlockHeaders query. */ BLOCK_BODIES(0x06), /** * {@code [+0x07 [blockHeader, transactionList, uncleList], totalDifficulty] } <br> * * Specify a single block that the peer should know about. The composite item * in the list (following the message ID) is a block in the format described * in the main Ethereum specification. */ NEW_BLOCK(0x07), /** * {@code [+0x0d, hash_0: B_32, hash_1: B_32, ...] } <br> * * Require peer to return a NodeData message. Hint that useful values in it * are those which correspond to given hashes. */ GET_NODE_DATA(0x0d), /** * {@code [+0x0e, value_0: B, value_1: B, ...] } <br> * * Provide a set of values which correspond to previously asked node data * hashes from GetNodeData. Does not need to contain all; best effort is * fine. If it contains none, then has no information for previous * GetNodeData hashes. */ NODE_DATA(0x0e), /** * {@code [+0x0f, hash_0: B_32, hash_1: B_32, ...] } <br> * * Require peer to return a Receipts message. Hint that useful values in it * are those which correspond to blocks of the given hashes. */ GET_RECEIPTS(0x0f), /** * {@code [+0x10, [receipt_0, receipt_1], ...] } <br> * * Provide a set of receipts which correspond to previously asked in GetReceipts. */ RECEIPTS(0x10); private int cmd; private static final Map<EthVersion, Map<Integer, EthMessageCodes>> intToTypeMap = new HashMap<>(); private static final Map<EthVersion, EthMessageCodes[]> versionToValuesMap = new HashMap<>(); static { versionToValuesMap.put(V62, new EthMessageCodes[]{ STATUS, NEW_BLOCK_HASHES, TRANSACTIONS, GET_BLOCK_HEADERS, BLOCK_HEADERS, GET_BLOCK_BODIES, BLOCK_BODIES, NEW_BLOCK }); versionToValuesMap.put(V63, new EthMessageCodes[]{ STATUS, NEW_BLOCK_HASHES, TRANSACTIONS, GET_BLOCK_HEADERS, BLOCK_HEADERS, GET_BLOCK_BODIES, BLOCK_BODIES, NEW_BLOCK, GET_NODE_DATA, NODE_DATA, GET_RECEIPTS, RECEIPTS }); for (EthVersion v : EthVersion.values()) { Map<Integer, EthMessageCodes> map = new HashMap<>(); intToTypeMap.put(v, map); for (EthMessageCodes code : values(v)) { map.put(code.cmd, code); } } } private EthMessageCodes(int cmd) { this.cmd = cmd; } public static EthMessageCodes[] values(EthVersion v) { return versionToValuesMap.get(v); } public static int maxCode(EthVersion v) { int max = 0; for (EthMessageCodes cd : versionToValuesMap.get(v)) if (max < cd.asByte()) max = cd.asByte(); return max; } public static EthMessageCodes fromByte(byte i, EthVersion v) { Map<Integer, EthMessageCodes> map = intToTypeMap.get(v); return map.get((int) i); } public static boolean inRange(byte code, EthVersion v) { EthMessageCodes[] codes = values(v); return code >= codes[0].asByte() && code <= codes[codes.length - 1].asByte(); } public byte asByte() { return (byte) (cmd); } }
8,321
33.53112
116
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/NewBlockMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.Block; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.math.BigInteger; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum Blocks message on the network * * @see EthMessageCodes#NEW_BLOCK */ public class NewBlockMessage extends EthMessage { private Block block; private byte[] difficulty; public NewBlockMessage(byte[] encoded) { super(encoded); } public NewBlockMessage(Block block, byte[] difficulty) { this.block = block; this.difficulty = difficulty; this.parsed = true; encode(); } private void encode() { byte[] block = this.block.getEncoded(); byte[] diff = RLP.encodeElement(this.difficulty); this.encoded = RLP.encodeList(block, diff); } private synchronized void parse() { if (parsed) return; RLPList paramsList = RLP.unwrapList(encoded); block = new Block(paramsList.get(0).getRLPData()); difficulty = paramsList.get(1).getRLPData(); parsed = true; } public Block getBlock() { parse(); return block; } public byte[] getDifficulty() { parse(); return difficulty; } public BigInteger getDifficultyAsBigInt() { return new BigInteger(1, difficulty); } @Override public byte[] getEncoded() { return encoded; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.NEW_BLOCK; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { parse(); String hash = this.getBlock().getShortHash(); long number = this.getBlock().getNumber(); return "NEW_BLOCK [ number: " + number + " hash:" + hash + " difficulty: " + toHexString(difficulty) + " ]"; } }
2,748
25.95098
116
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/GetBlockHeadersMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.BlockIdentifier; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.math.BigInteger; import static org.ethereum.util.ByteUtil.byteArrayToInt; import static org.ethereum.util.ByteUtil.byteArrayToLong; /** * Wrapper around an Ethereum GetBlockHeaders message on the network * * @see EthMessageCodes#GET_BLOCK_HEADERS * * @author Mikhail Kalinin * @since 04.09.2015 */ public class GetBlockHeadersMessage extends EthMessage { private static final int DEFAULT_SIZE_BYTES = 32; /** * Block number from which to start sending block headers */ private long blockNumber; /** * Block hash from which to start sending block headers <br> * Initial block can be addressed by either {@code blockNumber} or {@code blockHash} */ private byte[] blockHash; /** * The maximum number of headers to be returned. <br> * <b>Note:</b> the peer could return fewer. */ private int maxHeaders; /** * Blocks to skip between consecutive headers. <br> * Direction depends on {@code reverse} param. */ private int skipBlocks; /** * The direction of headers enumeration. <br> * <b>false</b> is for rising block numbers. <br> * <b>true</b> is for falling block numbers. */ private boolean reverse; public GetBlockHeadersMessage(byte[] encoded) { super(encoded); } public GetBlockHeadersMessage(long blockNumber, int maxHeaders) { this(blockNumber, null, maxHeaders, 0, false); } public GetBlockHeadersMessage(long blockNumber, byte[] blockHash, int maxHeaders, int skipBlocks, boolean reverse) { this.blockNumber = blockNumber; this.blockHash = blockHash; this.maxHeaders = maxHeaders; this.skipBlocks = skipBlocks; this.reverse = reverse; parsed = true; encode(); } private void encode() { byte[] maxHeaders = RLP.encodeInt(this.maxHeaders); byte[] skipBlocks = RLP.encodeInt(this.skipBlocks); byte[] reverse = RLP.encodeByte((byte) (this.reverse ? 1 : 0)); if (this.blockHash != null) { byte[] hash = RLP.encodeElement(this.blockHash); this.encoded = RLP.encodeList(hash, maxHeaders, skipBlocks, reverse); } else { byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.blockNumber)); this.encoded = RLP.encodeList(number, maxHeaders, skipBlocks, reverse); } } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); byte[] blockBytes = paramsList.get(0).getRLPData(); // it might be either a hash or number if (blockBytes == null) { this.blockNumber = 0; } else if (blockBytes.length == DEFAULT_SIZE_BYTES) { this.blockHash = blockBytes; } else { this.blockNumber = byteArrayToLong(blockBytes); } byte[] maxHeaders = paramsList.get(1).getRLPData(); this.maxHeaders = byteArrayToInt(maxHeaders); byte[] skipBlocks = paramsList.get(2).getRLPData(); this.skipBlocks = byteArrayToInt(skipBlocks); byte[] reverse = paramsList.get(3).getRLPData(); this.reverse = byteArrayToInt(reverse) == 1; parsed = true; } public long getBlockNumber() { parse(); return blockNumber; } public byte[] getBlockHash() { parse(); return blockHash; } public BlockIdentifier getBlockIdentifier() { parse(); return new BlockIdentifier(blockHash, blockNumber); } public int getMaxHeaders() { parse(); return maxHeaders; } public int getSkipBlocks() { parse(); return skipBlocks; } public boolean isReverse() { parse(); return reverse; } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<BlockHeadersMessage> getAnswerMessage() { return BlockHeadersMessage.class; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.GET_BLOCK_HEADERS; } @Override public String toString() { parse(); return "[" + this.getCommand().name() + " blockNumber=" + String.valueOf(blockNumber) + " blockHash=" + ByteUtil.toHexString(blockHash) + " maxHeaders=" + maxHeaders + " skipBlocks=" + skipBlocks + " reverse=" + reverse + "]"; } }
5,561
28.585106
120
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/NewBlockHashesMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.core.BlockIdentifier; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import java.util.ArrayList; import java.util.List; /** * Wrapper around an Ethereum NewBlockHashes message on the network<br> * * @see EthMessageCodes#NEW_BLOCK_HASHES * * @author Mikhail Kalinin * @since 05.09.2015 */ public class NewBlockHashesMessage extends EthMessage { /** * List of identifiers holding hash and number of the blocks */ private List<BlockIdentifier> blockIdentifiers; public NewBlockHashesMessage(byte[] payload) { super(payload); } public NewBlockHashesMessage(List<BlockIdentifier> blockIdentifiers) { this.blockIdentifiers = blockIdentifiers; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); blockIdentifiers = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { RLPList rlpData = ((RLPList) paramsList.get(i)); blockIdentifiers.add(new BlockIdentifier(rlpData)); } parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (BlockIdentifier identifier : blockIdentifiers) encodedElements.add(identifier.getEncoded()); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<?> getAnswerMessage() { return null; } public List<BlockIdentifier> getBlockIdentifiers() { parse(); return blockIdentifiers; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.NEW_BLOCK_HASHES; } @Override public String toString() { parse(); return "[" + this.getCommand().name() + "] (" + blockIdentifiers.size() + ")"; } }
2,950
28.217822
99
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/GetNodeDataMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.ethereum.util.Utils; import java.util.ArrayList; import java.util.List; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum GetNodeData message on the network * Could contain: * - state roots * - accounts state roots * - accounts code hashes * * @see EthMessageCodes#GET_NODE_DATA */ public class GetNodeDataMessage extends EthMessage { /** * List of node hashes for which is state requested */ private List<byte[]> nodeKeys; public GetNodeDataMessage(byte[] encoded) { super(encoded); } public GetNodeDataMessage(List<byte[]> nodeKeys) { this.nodeKeys = nodeKeys; this.parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); this.nodeKeys = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { nodeKeys.add(paramsList.get(i).getRLPData()); } this.parsed = true; } private void encode() { List<byte[]> encodedElements = new ArrayList<>(); for (byte[] hash : nodeKeys) encodedElements.add(RLP.encodeElement(hash)); byte[][] encodedElementArray = encodedElements.toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<NodeDataMessage> getAnswerMessage() { return NodeDataMessage.class; } public List<byte[]> getNodeKeys() { parse(); return nodeKeys; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.GET_NODE_DATA; } public String toString() { parse(); StringBuilder payload = new StringBuilder(); payload.append("count( ").append(nodeKeys.size()).append(" ) "); if (logger.isDebugEnabled()) { for (byte[] hash : nodeKeys) { payload.append(toHexString(hash).substring(0, 6)).append(" | "); } if (!nodeKeys.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } else { payload.append(Utils.getHashListShort(nodeKeys)); } return "[" + getCommand().name() + " " + payload + "]"; } }
3,357
27.457627
99
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/BlockBodiesMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; import java.util.ArrayList; import java.util.List; import static org.ethereum.util.ByteUtil.toHexString; /** * Wrapper around an Ethereum BlockBodies message on the network * * @see EthMessageCodes#BLOCK_BODIES * * @author Mikhail Kalinin * @since 04.09.2015 */ public class BlockBodiesMessage extends EthMessage { private List<byte[]> blockBodies; public BlockBodiesMessage(byte[] encoded) { super(encoded); } public BlockBodiesMessage(List<byte[]> blockBodies) { this.blockBodies = blockBodies; parsed = true; } private synchronized void parse() { if (parsed) return; RLPList paramsList = RLP.unwrapList(encoded); this.encoded = null; blockBodies = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { RLPElement rlpData = paramsList.get(i); blockBodies.add(rlpData.getRLPData()); } parsed = true; } private void encode() { byte[][] encodedElementArray = blockBodies .toArray(new byte[blockBodies.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public List<byte[]> getBlockBodies() { parse(); return blockBodies; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.BLOCK_BODIES; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { parse(); StringBuilder payload = new StringBuilder(); payload.append("count( ").append(blockBodies.size()).append(" )"); if (logger.isTraceEnabled()) { payload.append(" "); for (byte[] body : blockBodies) { payload.append(toHexString(body)).append(" | "); } if (!blockBodies.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } return "[" + getCommand().name() + " " + payload + "]"; } }
3,088
26.580357
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/eth/message/NodeDataMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.message; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.ethereum.util.Value; import java.util.ArrayList; import java.util.List; /** * Wrapper around an Ethereum NodeData message on the network * * @see EthMessageCodes#NODE_DATA */ public class NodeDataMessage extends EthMessage { private List<Value> dataList; public NodeDataMessage(byte[] encoded) { super(encoded); parse(); } public NodeDataMessage(List<Value> dataList) { this.dataList = dataList; parsed = true; } private void parse() { RLPList paramsList = RLP.unwrapList(encoded); dataList = new ArrayList<>(); for (int i = 0; i < paramsList.size(); ++i) { // Need it AS IS dataList.add(new Value(paramsList.get(i).getRLPData())); } parsed = true; } private void encode() { List<byte[]> dataListRLP = new ArrayList<>(); for (Value value: dataList) { if (value == null) continue; // Bad sign dataListRLP.add(RLP.encodeElement(value.asBytes())); } byte[][] encodedElementArray = dataListRLP.toArray(new byte[dataListRLP.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public List<Value> getDataList() { return dataList; } @Override public EthMessageCodes getCommand() { return EthMessageCodes.NODE_DATA; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { StringBuilder payload = new StringBuilder(); payload.append("count( ").append(dataList.size()).append(" )"); if (logger.isTraceEnabled()) { payload.append(" "); for (Value value : dataList) { payload.append(value).append(" | "); } if (!dataList.isEmpty()) { payload.delete(payload.length() - 3, payload.length()); } } return "[" + getCommand().name() + " " + payload + "]"; } }
3,024
27.271028
91
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/dht/Peer.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.dht; import org.ethereum.crypto.HashUtil; import org.spongycastle.util.BigIntegers; import java.math.BigInteger; import static org.ethereum.util.ByteUtil.toHexString; public class Peer { byte[] id; String host = "127.0.0.1"; int port = 0; public Peer(byte[] id, String host, int port) { this.id = id; this.host = host; this.port = port; } public Peer(byte[] ip) { this.id= ip; } public Peer() { HashUtil.randomPeerId(); } public byte nextBit(String startPattern) { if (this.toBinaryString().startsWith(startPattern + "1")) return 1; else return 0; } public byte[] calcDistance(Peer toPeer) { BigInteger aPeer = new BigInteger(getId()); BigInteger bPeer = new BigInteger(toPeer.getId()); BigInteger distance = aPeer.xor(bPeer); return BigIntegers.asUnsignedByteArray(distance); } public byte[] getId() { return id; } public void setId(byte[] id) { this.id = id; } @Override public String toString() { return String.format("Peer {\n id=%s, \n host=%s, \n port=%d\n}", toHexString(id), host, port); } public String toBinaryString() { BigInteger bi = new BigInteger(1, id); String out = String.format("%512s", bi.toString(2)); out = out.replace(' ', '0'); return out; } }
2,258
25.267442
103
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/dht/Bucket.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.dht; import java.util.ArrayList; import java.util.List; public class Bucket { public static int MAX_KADEMLIA_K = 5; // if bit = 1 go left Bucket left; // if bit = 0 go right Bucket right; String name; List<Peer> peers = new ArrayList<>(); public Bucket(String name) { this.name = name; } public void add(Peer peer) { if (peer == null) throw new Error("Not a leaf"); if ( peers == null){ if (peer.nextBit(name) == 1) left.add(peer); else right.add(peer); return; } peers.add(peer); if (peers.size() > MAX_KADEMLIA_K) splitBucket(); } public void splitBucket() { left = new Bucket(name + "1"); right = new Bucket(name + "0"); for (Peer id : peers) { if (id.nextBit(name) == 1) left.add(id); else right.add(id); } this.peers = null; } public Bucket left() { return left; } public Bucket right() { return right; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(name).append("\n"); if (peers == null) return sb.toString(); for (Peer id : peers) sb.append(id.toBinaryString()).append("\n"); return sb.toString(); } public void traverseTree(DoOnTree doOnTree) { if (left != null) left.traverseTree(doOnTree); if (right != null) right.traverseTree(doOnTree); doOnTree.call(this); } /********************/ // tree operations // /********************/ public interface DoOnTree { void call(Bucket bucket); } public static class SaveLeaf implements DoOnTree { List<Bucket> leafs = new ArrayList<>(); @Override public void call(Bucket bucket) { if (bucket.peers != null) leafs.add(bucket); } public List<Bucket> getLeafs() { return leafs; } public void setLeafs(List<Bucket> leafs) { this.leafs = leafs; } } public String getName(){ return name; } public List<Peer> getPeers() { return peers; } }
3,160
20.358108
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/dht/DHTUtils.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.dht; import java.util.List; import static org.ethereum.net.dht.Bucket.*; public class DHTUtils { public static void printAllLeafs(Bucket root){ SaveLeaf saveLeaf = new SaveLeaf(); root.traverseTree(saveLeaf); for (Bucket bucket : saveLeaf.getLeafs()) System.out.println(bucket); } public static List<Bucket> getAllLeafs(Bucket root){ SaveLeaf saveLeaf = new SaveLeaf(); root.traverseTree(saveLeaf); return saveLeaf.getLeafs(); } }
1,329
31.439024
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/PongMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Pong message on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#PONG */ public class PongMessage extends P2pMessage { /** * Pong message is always a the same single command payload */ private final static byte[] FIXED_PAYLOAD = Hex.decode("C0"); @Override public byte[] getEncoded() { return FIXED_PAYLOAD; } @Override public Class<?> getAnswerMessage() { return null; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.PONG; } @Override public String toString() { return "[" + this.getCommand().name() + "]"; } }
1,550
28.264151
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageCodes.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import java.util.HashMap; import java.util.Map; /** * A list of commands for the Ethereum network protocol. * <br> * The codes for these commands are the first byte in every packet. * ÐΞV * * @see <a href="https://github.com/ethereum/wiki/wiki/%C3%90%CE%9EVp2p-Wire-Protocol"> * https://github.com/ethereum/wiki/wiki/ÐΞVp2p-Wire-Protocol</a> */ public enum P2pMessageCodes { /* P2P protocol */ /** * [0x00, P2P_VERSION, CLIEND_ID, CAPS, LISTEN_PORT, CLIENT_ID] <br> * First packet sent over the connection, and sent once by both sides. * No other messages may be sent until a Hello is received. */ HELLO(0x00), /** * [0x01, REASON] <br>Inform the peer that a disconnection is imminent; * if received, a peer should disconnect immediately. When sending, * well-behaved hosts give their peers a fighting chance (read: wait 2 seconds) * to disconnect to before disconnecting themselves. */ DISCONNECT(0x01), /** * [0x02] <br>Requests an immediate reply of Pong from the peer. */ PING(0x02), /** * [0x03] <br>Reply to peer's Ping packet. */ PONG(0x03), /** * [0x04] <br>Request the peer to enumerate some known peers * for us to connect to. This should include the peer itself. */ GET_PEERS(0x04), /** * [0x05, [IP1, Port1, Id1], [IP2, Port2, Id2], ... ] <br> * Specifies a number of known peers. IP is a 4-byte array 'ABCD' * that should be interpreted as the IP address A.B.C.D. * Port is a 2-byte array that should be interpreted as a * 16-bit big-endian integer. Id is the 512-bit hash that acts * as the unique identifier of the node. */ PEERS(0x05), /** * */ USER(0x0F); private final int cmd; private static final Map<Integer, P2pMessageCodes> intToTypeMap = new HashMap<>(); static { for (P2pMessageCodes type : P2pMessageCodes.values()) { intToTypeMap.put(type.cmd, type); } } private P2pMessageCodes(int cmd) { this.cmd = cmd; } public static P2pMessageCodes fromByte(byte i) { return intToTypeMap.get((int) i); } public static boolean inRange(byte code) { return code >= HELLO.asByte() && code <= USER.asByte(); } public byte asByte() { return (byte) (cmd); } }
3,210
27.927928
87
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/Peer.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.net.client.Capability; import org.ethereum.util.RLP; import org.spongycastle.util.encoders.Hex; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; /** * This class models a peer in the network */ public class Peer { private final InetAddress address; private final int port; private final String peerId; private final List<Capability> capabilities; public Peer(InetAddress ip, int port, String peerId) { this.address = ip; this.port = port; this.peerId = peerId; this.capabilities = new ArrayList<>(); } public InetAddress getAddress() { return address; } public int getPort() { return port; } public String getPeerId() { return peerId == null ? "" : peerId; } public List<Capability> getCapabilities() { return capabilities; } public byte[] getEncoded() { byte[] ip = RLP.encodeElement(this.address.getAddress()); byte[] port = RLP.encodeInt(this.port); byte[] peerId = RLP.encodeElement(Hex.decode(this.peerId)); byte[][] encodedCaps = new byte[this.capabilities.size()][]; for (int i = 0; i < this.capabilities.size() * 2; i++) { encodedCaps[i] = RLP.encodeString(this.capabilities.get(i).getName()); encodedCaps[i] = RLP.encodeByte(this.capabilities.get(i).getVersion()); } byte[] capabilities = RLP.encodeList(encodedCaps); return RLP.encodeList(ip, port, peerId, capabilities); } @Override public String toString() { return "[ip=" + getAddress().getHostAddress() + " port=" + getPort() + " peerId=" + getPeerId() + "]"; } @Override public boolean equals(Object obj) { if(!(obj instanceof Peer)) return false; Peer peerData = (Peer) obj; return peerData.peerId.equals(this.peerId) || this.getAddress().equals(peerData.getAddress()); } @Override public int hashCode() { int result = peerId.hashCode(); result = 31 * result + address.hashCode(); result = 31 * result + port; return result; } }
3,045
30.402062
83
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import com.google.common.base.Joiner; import org.ethereum.net.client.Capability; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; import org.spongycastle.util.encoders.Hex; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; /** * Wrapper around an Ethereum HelloMessage on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#HELLO */ public class HelloMessage extends P2pMessage { /** * The implemented version of the P2P protocol. */ private byte p2pVersion; /** * The underlying client. A user-readable string. */ private String clientId; /** * A peer-network capability code, readable ASCII and 3 letters. * Currently only "eth", "shh" and "bzz" are known. */ private List<Capability> capabilities = Collections.emptyList(); /** * The port on which the peer is listening for an incoming connection */ private int listenPort; /** * The identity and public key of the peer */ private String peerId; public HelloMessage(byte[] encoded) { super(encoded); } public HelloMessage(byte p2pVersion, String clientId, List<Capability> capabilities, int listenPort, String peerId) { this.p2pVersion = p2pVersion; this.clientId = clientId; this.capabilities = capabilities; this.listenPort = listenPort; this.peerId = peerId; this.parsed = true; } private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); byte[] p2pVersionBytes = paramsList.get(0).getRLPData(); this.p2pVersion = p2pVersionBytes != null ? p2pVersionBytes[0] : 0; byte[] clientIdBytes = paramsList.get(1).getRLPData(); this.clientId = new String(clientIdBytes != null ? clientIdBytes : EMPTY_BYTE_ARRAY); RLPList capabilityList = (RLPList) paramsList.get(2); this.capabilities = new ArrayList<>(); for (Object aCapabilityList : capabilityList) { RLPElement capId = ((RLPList) aCapabilityList).get(0); RLPElement capVersion = ((RLPList) aCapabilityList).get(1); String name = new String(capId.getRLPData()); byte version = capVersion.getRLPData() == null ? 0 : capVersion.getRLPData()[0]; Capability cap = new Capability(name, version); this.capabilities.add(cap); } byte[] peerPortBytes = paramsList.get(3).getRLPData(); this.listenPort = ByteUtil.byteArrayToInt(peerPortBytes); byte[] peerIdBytes = paramsList.get(4).getRLPData(); this.peerId = Hex.toHexString(peerIdBytes); this.parsed = true; } private void encode() { byte[] p2pVersion = RLP.encodeByte(this.p2pVersion); byte[] clientId = RLP.encodeString(this.clientId); byte[][] capabilities = new byte[this.capabilities.size()][]; for (int i = 0; i < this.capabilities.size(); i++) { Capability capability = this.capabilities.get(i); capabilities[i] = RLP.encodeList( RLP.encodeElement(capability.getName().getBytes()), RLP.encodeInt(capability.getVersion())); } byte[] capabilityList = RLP.encodeList(capabilities); byte[] peerPort = RLP.encodeInt(this.listenPort); byte[] peerId = RLP.encodeElement(Hex.decode(this.peerId)); this.encoded = RLP.encodeList(p2pVersion, clientId, capabilityList, peerPort, peerId); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public byte getP2PVersion() { if (!parsed) parse(); return p2pVersion; } public String getClientId() { if (!parsed) parse(); return clientId; } public List<Capability> getCapabilities() { if (!parsed) parse(); return capabilities; } public int getListenPort() { if (!parsed) parse(); return listenPort; } public String getPeerId() { if (!parsed) parse(); return peerId; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.HELLO; } public void setPeerId(String peerId) { this.peerId = peerId; } public void setP2pVersion(byte p2pVersion) { this.p2pVersion = p2pVersion; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { if (!parsed) parse(); return "[" + this.getCommand().name() + " p2pVersion=" + this.p2pVersion + " clientId=" + this.clientId + " capabilities=[" + Joiner.on(" ").join(this.capabilities) + "]" + " peerPort=" + this.listenPort + " peerId=" + this.peerId + "]"; } }
5,873
31.098361
93
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/PingMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Ping message on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#PING */ public class PingMessage extends P2pMessage { /** * Ping message is always a the same single command payload */ private final static byte[] FIXED_PAYLOAD = Hex.decode("C0"); public byte[] getEncoded() { return FIXED_PAYLOAD; } @Override public Class<PongMessage> getAnswerMessage() { return PongMessage.class; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.PING; } @Override public String toString() { return "[" + getCommand().name() + "]"; } }
1,554
28.903846
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/DisconnectMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.net.message.ReasonCode; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import static org.ethereum.net.message.ReasonCode.REQUESTED; import static org.ethereum.net.message.ReasonCode.UNKNOWN; import static org.ethereum.net.p2p.P2pMessageCodes.DISCONNECT; /** * Wrapper around an Ethereum Disconnect message on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#DISCONNECT */ public class DisconnectMessage extends P2pMessage { private ReasonCode reason; public DisconnectMessage(byte[] encoded) { super(encoded); } public DisconnectMessage(ReasonCode reason) { this.reason = reason; parsed = true; } private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); if (paramsList.size() > 0) { byte[] reasonBytes = paramsList.get(0).getRLPData(); if (reasonBytes == null) this.reason = UNKNOWN; else this.reason = ReasonCode.fromInt(reasonBytes[0]); } else { this.reason = UNKNOWN; } parsed = true; } private void encode() { byte[] encodedReason = RLP.encodeByte(this.reason.asByte()); this.encoded = RLP.encodeList(encodedReason); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.DISCONNECT; } @Override public Class<?> getAnswerMessage() { return null; } public ReasonCode getReason() { if (!parsed) parse(); return reason; } public String toString() { if (!parsed) parse(); return "[" + this.getCommand().name() + " reason=" + reason + "]"; } }
2,671
28.043478
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.net.message.Message; public abstract class P2pMessage extends Message { public P2pMessage() { } public P2pMessage(byte[] encoded) { super(encoded); } public P2pMessageCodes getCommand() { return P2pMessageCodes.fromByte(code); } }
1,116
30.914286
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageFactory.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.net.message.Message; import org.ethereum.net.message.MessageFactory; import org.ethereum.net.message.StaticMessages; /** * P2P message factory * * @author Mikhail Kalinin * @since 20.08.2015 */ public class P2pMessageFactory implements MessageFactory { @Override public Message create(byte code, byte[] encoded) { P2pMessageCodes receivedCommand = P2pMessageCodes.fromByte(code); switch (receivedCommand) { case HELLO: return new HelloMessage(encoded); case DISCONNECT: return new DisconnectMessage(encoded); case PING: return StaticMessages.PING_MESSAGE; case PONG: return StaticMessages.PONG_MESSAGE; case GET_PEERS: return StaticMessages.GET_PEERS_MESSAGE; case PEERS: return new PeersMessage(encoded); default: throw new IllegalArgumentException("No such message"); } } }
1,857
33.407407
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.Transaction; import org.ethereum.listener.EthereumListener; import org.ethereum.manager.WorldManager; import org.ethereum.net.MessageQueue; import org.ethereum.net.client.Capability; import org.ethereum.net.client.ConfigCapabilities; import org.ethereum.net.eth.message.NewBlockMessage; import org.ethereum.net.eth.message.TransactionsMessage; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.message.StaticMessages; import org.ethereum.net.server.Channel; import org.ethereum.net.shh.ShhHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.ethereum.net.swarm.Util; import org.ethereum.net.swarm.bzz.BzzHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; import static org.ethereum.net.eth.EthVersion.*; import static org.ethereum.net.message.StaticMessages.*; /** * Process the basic protocol messages between every peer on the network. * * Peers can send/receive * <ul> * <li>HELLO : Announce themselves to the network</li> * <li>DISCONNECT : Disconnect themselves from the network</li> * <li>GET_PEERS : Request a list of other knows peers</li> * <li>PEERS : Send a list of known peers</li> * <li>PING : Check if another peer is still alive</li> * <li>PONG : Confirm that they themselves are still alive</li> * </ul> */ @Component @Scope("prototype") public class P2pHandler extends SimpleChannelInboundHandler<P2pMessage> { public final static byte VERSION = 5; private final static Logger logger = LoggerFactory.getLogger("net"); private static ScheduledExecutorService pingTimer = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "P2pPingTimer")); private MessageQueue msgQueue; private boolean peerDiscoveryMode = false; private HelloMessage handshakeHelloMessage = null; private int ethInbound; private int ethOutbound; @Autowired EthereumListener ethereumListener; @Autowired ConfigCapabilities configCapabilities; @Autowired SystemProperties config; private Channel channel; private ScheduledFuture<?> pingTask; public P2pHandler() { this.peerDiscoveryMode = false; } public P2pHandler(MessageQueue msgQueue, boolean peerDiscoveryMode) { this.msgQueue = msgQueue; this.peerDiscoveryMode = peerDiscoveryMode; } public void setPeerDiscoveryMode(boolean peerDiscoveryMode) { this.peerDiscoveryMode = peerDiscoveryMode; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { logger.debug("P2P protocol activated"); msgQueue.activate(ctx); ethereumListener.trace("P2P protocol activated"); startTimers(); } @Override public void channelRead0(final ChannelHandlerContext ctx, P2pMessage msg) throws InterruptedException { if (P2pMessageCodes.inRange(msg.getCommand().asByte())) logger.trace("P2PHandler invoke: [{}]", msg.getCommand()); ethereumListener.trace(String.format("P2PHandler invoke: [%s]", msg.getCommand())); switch (msg.getCommand()) { case HELLO: msgQueue.receivedMessage(msg); setHandshake((HelloMessage) msg, ctx); // sendGetPeers(); break; case DISCONNECT: msgQueue.receivedMessage(msg); channel.getNodeStatistics().nodeDisconnectedRemote(((DisconnectMessage) msg).getReason()); processDisconnect(ctx, (DisconnectMessage) msg); break; case PING: msgQueue.receivedMessage(msg); ctx.writeAndFlush(PONG_MESSAGE); break; case PONG: msgQueue.receivedMessage(msg); channel.getNodeStatistics().lastPongReplyTime.set(Util.curTime()); break; case PEERS: msgQueue.receivedMessage(msg); if (peerDiscoveryMode || !handshakeHelloMessage.getCapabilities().contains(Capability.ETH)) { disconnect(ReasonCode.REQUESTED); killTimers(); ctx.close().sync(); ctx.disconnect().sync(); } break; default: ctx.fireChannelRead(msg); break; } } private void disconnect(ReasonCode reasonCode) { msgQueue.sendMessage(new DisconnectMessage(reasonCode)); channel.getNodeStatistics().nodeDisconnectedLocal(reasonCode); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.debug("channel inactive: ", ctx.toString()); this.killTimers(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn("P2p handling failed", cause); ctx.close(); killTimers(); } private void processDisconnect(ChannelHandlerContext ctx, DisconnectMessage msg) { if (logger.isInfoEnabled() && msg.getReason() == ReasonCode.USELESS_PEER) { if (channel.getNodeStatistics().ethInbound.get() - ethInbound > 1 || channel.getNodeStatistics().ethOutbound.get() - ethOutbound > 1) { // it means that we've been disconnected // after some incorrect action from our peer // need to log this moment logger.debug("From: \t{}\t [DISCONNECT reason=BAD_PEER_ACTION]", channel); } } ctx.close(); killTimers(); } private void sendGetPeers() { msgQueue.sendMessage(StaticMessages.GET_PEERS_MESSAGE); } public void setHandshake(HelloMessage msg, ChannelHandlerContext ctx) { channel.getNodeStatistics().setClientId(msg.getClientId()); channel.getNodeStatistics().capabilities.clear(); channel.getNodeStatistics().capabilities.addAll(msg.getCapabilities()); this.ethInbound = (int) channel.getNodeStatistics().ethInbound.get(); this.ethOutbound = (int) channel.getNodeStatistics().ethOutbound.get(); this.handshakeHelloMessage = msg; List<Capability> capInCommon = getSupportedCapabilities(msg); channel.initMessageCodes(capInCommon); for (Capability capability : capInCommon) { if (capability.getName().equals(Capability.ETH)) { // Activate EthHandler for this peer channel.activateEth(ctx, fromCode(capability.getVersion())); } else if (capability.getName().equals(Capability.SHH) && capability.getVersion() == ShhHandler.VERSION) { // Activate ShhHandler for this peer channel.activateShh(ctx); } else if (capability.getName().equals(Capability.BZZ) && capability.getVersion() == BzzHandler.VERSION) { // Activate ShhHandler for this peer channel.activateBzz(ctx); } } //todo calculate the Offsets ethereumListener.onHandShakePeer(channel, msg); } /** * submit transaction to the network * * @param tx - fresh transaction object */ public void sendTransaction(Transaction tx) { TransactionsMessage msg = new TransactionsMessage(tx); msgQueue.sendMessage(msg); } public void sendNewBlock(Block block) { NewBlockMessage msg = new NewBlockMessage(block, block.getDifficulty()); msgQueue.sendMessage(msg); } public void sendDisconnect() { msgQueue.disconnect(); } public HelloMessage getHandshakeHelloMessage() { return handshakeHelloMessage; } private void startTimers() { // sample for pinging in background pingTask = pingTimer.scheduleAtFixedRate(() -> { try { msgQueue.sendMessage(PING_MESSAGE); } catch (Throwable t) { logger.error("Unhandled exception", t); } }, 2, config.getProperty("peer.p2p.pingInterval", 5), TimeUnit.SECONDS); } public void killTimers() { pingTask.cancel(false); msgQueue.close(); } public void setMsgQueue(MessageQueue msgQueue) { this.msgQueue = msgQueue; } public void setChannel(Channel channel) { this.channel = channel; } public List<Capability> getSupportedCapabilities(HelloMessage hello) { List<Capability> configCaps = configCapabilities.getConfigCapabilities(); List<Capability> supported = new ArrayList<>(); List<Capability> eths = new ArrayList<>(); for (Capability cap : hello.getCapabilities()) { if (configCaps.contains(cap)) { if (cap.isEth()) { eths.add(cap); } else { supported.add(cap); } } } if (eths.isEmpty()) { return supported; } // we need to pick up // the most recent Eth version Capability highest = null; for (Capability eth : eths) { if (highest == null || highest.getVersion() < eth.getVersion()) { highest = eth; } } supported.add(highest); return supported; } }
10,849
31.38806
107
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/GetPeersMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum GetPeers message on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#GET_PEERS */ public class GetPeersMessage extends P2pMessage { /** * GetPeers message is always a the same single command payload */ private final static byte[] FIXED_PAYLOAD = Hex.decode("C104"); @Override public byte[] getEncoded() { return FIXED_PAYLOAD; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.GET_PEERS; } @Override public Class<PeersMessage> getAnswerMessage() { return null; } @Override public String toString() { return "[" + this.getCommand().name() + "]"; } }
1,585
28.924528
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/p2p/PeersMessage.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.spongycastle.util.encoders.Hex; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Wrapper around an Ethereum Peers message on the network * * @see org.ethereum.net.p2p.P2pMessageCodes#PEERS */ public class PeersMessage extends P2pMessage { private boolean parsed = false; private Set<Peer> peers; public PeersMessage(byte[] payload) { super(payload); } public PeersMessage(Set<Peer> peers) { this.peers = peers; parsed = true; } private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); peers = new LinkedHashSet<>(); for (int i = 1; i < paramsList.size(); ++i) { RLPList peerParams = (RLPList) paramsList.get(i); byte[] ipBytes = peerParams.get(0).getRLPData(); byte[] portBytes = peerParams.get(1).getRLPData(); byte[] peerIdRaw = peerParams.get(2).getRLPData(); try { int peerPort = ByteUtil.byteArrayToInt(portBytes); InetAddress address = InetAddress.getByAddress(ipBytes); String peerId = peerIdRaw == null ? "" : Hex.toHexString(peerIdRaw); Peer peer = new Peer(address, peerPort, peerId); peers.add(peer); } catch (UnknownHostException e) { throw new RuntimeException("Malformed ip", e); } } this.parsed = true; } private void encode() { byte[][] encodedByteArrays = new byte[this.peers.size() + 1][]; encodedByteArrays[0] = RLP.encodeByte(this.getCommand().asByte()); List<Peer> peerList = new ArrayList<>(this.peers); for (int i = 0; i < peerList.size(); i++) { encodedByteArrays[i + 1] = peerList.get(i).getEncoded(); } this.encoded = RLP.encodeList(encodedByteArrays); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } public Set<Peer> getPeers() { if (!parsed) this.parse(); return peers; } @Override public P2pMessageCodes getCommand() { return P2pMessageCodes.PEERS; } @Override public Class<?> getAnswerMessage() { return null; } public String toString() { if (!parsed) this.parse(); StringBuilder sb = new StringBuilder(); for (Peer peerData : peers) { sb.append("\n ").append(peerData); } return "[" + this.getCommand().name() + sb.toString() + "]"; } }
3,620
29.686441
84
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/DBStore.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.datasource.DbSource; /** * ChunkStore backed up with KeyValueDataSource * * Created by Admin on 18.06.2015. */ public class DBStore implements ChunkStore { private DbSource<byte[]> db; public DBStore(DbSource db) { this.db = db; } @Override public void put(Chunk chunk) { db.put(chunk.getKey().getBytes(), chunk.getData()); } @Override public Chunk get(Key key) { byte[] bytes = db.get(key.getBytes()); return bytes == null ? null : new Chunk(key, bytes); } }
1,379
29.666667
80
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Chunker.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import java.util.Collection; /** * Chunker is the interface to a component that is responsible for disassembling and assembling larger data * and intended to be the dependency of a DPA storage system with fixed maximum chunksize. * It relies on the underlying chunking model. * When calling Split, the caller provides a channel (chan *Chunk) on which it receives chunks to store. * The DPA delegates to storage layers (implementing ChunkStore interface). NewChunkstore(DB) is a convenience * wrapper with which all DBs (conforming to DB interface) can serve as ChunkStores. See chunkStore.go * * After getting notified that all the data has been split (the error channel is closed), the caller can safely * read or save the root key. Optionally it times out if not all chunks get stored or not the entire stream * of data has been processed. By inspecting the errc channel the caller can check if any explicit errors * (typically IO read/write failures) occurred during splitting. * * When calling Join with a root key, the caller gets returned a lazy reader. The caller again provides a channel * and receives an error channel. The chunk channel is the one on which the caller receives placeholder chunks with * missing data. The DPA is supposed to forward this to the chunk stores and notify the chunker if the data * has been delivered (i.e. retrieved from memory cache, disk-persisted db or cloud based swarm delivery). * The chunker then puts these together and notifies the DPA if data has been assembled by a closed error channel. * Once the DPA finds the data has been joined, it is free to deliver it back to swarm in full (if the original * request was via the bzz protocol) or save and serve if it it was a local client request. */ public interface Chunker { /** * When splitting, data is given as a SectionReader, and the key is a hashSize long byte slice (Key), * the root hash of the entire content will fill this once processing finishes. * New chunks to store are coming to caller via the chunk storage channel, which the caller provides. * wg is a Waitgroup (can be nil) that can be used to block until the local storage finishes * The caller gets returned an error channel, if an error is encountered during splitting, it is fed to errC error channel. * A closed error signals process completion at which point the key can be considered final if there were no errors. */ Key split(SectionReader sectionReader, Collection<Chunk> consumer); /** * Join reconstructs original content based on a root key. * When joining, the caller gets returned a Lazy SectionReader * New chunks to retrieve are coming to caller via the Chunk channel, which the caller provides. * If an error is encountered during joining, it appears as a reader error. * The SectionReader provides on-demand fetching of chunks. */ SectionReader join(ChunkStore chunkStore, Key key); /** * @return the key length */ long keySize(); }
3,862
54.985507
127
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Statter.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; /** * The interface for gathering statistical information. * Used similar to loggers and assumed to have minimal latency to * not affect the performance in production. * The implementation might be substituted to allow some advanced * information processing like streaming it to the database * or aggregating and displaying as graphics * * Created by Anton Nashatyrev on 01.07.2015. */ public abstract class Statter { public static class SimpleStatter extends Statter { private final String name; private volatile double last; private volatile double sum; private volatile int count; public SimpleStatter(String name) { this.name = name; } @Override public void add(double value) { last = value; sum += value; count++; } public double getLast() { return last; } public int getCount() { return count; } public double getSum() { return sum; } public double getAvrg() { return getSum() / getCount(); } public String getName() { return name; } } /** * Used as a factory to create statters. * @param name Normally the name is assumed to be a hierarchical path with '.' delimiters * similar to full Java class names. */ public static Statter create(String name) { return new SimpleStatter(name); } public abstract void add(double value); }
2,403
27.619048
93
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/Manifest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; /** * Hierarchical structure of path items * The item can be one of two kinds: * - the leaf item which contains reference to the actual data with its content type * - the non-leaf item which contains reference to the child manifest with the dedicated content type */ public class Manifest { public enum Status { OK(200), NOT_FOUND(404); private int code; Status(int code) { this.code = code; } } // used for Json [de]serialization only private static class ManifestRoot { public List<ManifestEntry> entries = new ArrayList<>(); public ManifestRoot() { } public ManifestRoot(List<ManifestEntry> entries) { this.entries = entries; } public ManifestRoot(ManifestEntry parent) { entries.addAll(parent.getChildren()); } } /** * Manifest item */ @JsonAutoDetect(getterVisibility= JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, isGetterVisibility = JsonAutoDetect.Visibility.NONE) public static class ManifestEntry extends StringTrie.TrieNode<ManifestEntry> { public String hash; public String contentType; public Status status; private Manifest thisMF; public ManifestEntry() { super(null, ""); } public ManifestEntry(String path, String hash, String contentType, Status status) { super(null, ""); this.path = path; this.hash = hash; this.contentType = contentType; this.status = status; } ManifestEntry(ManifestEntry parent, String path) { super(parent, path); this.path = path; } /** * Indicates if this entry contains reference to a child manifest */ public boolean isManifestType() { return MANIFEST_MIME_TYPE.equals(contentType);} boolean isValid() {return hash != null;} void invalidate() {hash = null;} @Override public boolean isLeaf() { return !(isManifestType() || !children.isEmpty()); } /** * loads the child manifest */ @Override protected Map<String, ManifestEntry> loadChildren() { if (isManifestType() && children.isEmpty() && isValid()) { ManifestRoot manifestRoot = load(thisMF.dpa, hash); children = new HashMap<>(); for (Manifest.ManifestEntry entry : manifestRoot.entries) { children.put(getKey(entry.path), entry); } } return children; } @JsonProperty public String getPath() { return path; } @JsonProperty public void setPath(String path) { this.path = path; } @Override protected ManifestEntry createNode(ManifestEntry parent, String path) { return new ManifestEntry(parent, path).setThisMF(parent.thisMF); } @Override protected void nodeChanged() { if (!isLeaf()) { contentType = MANIFEST_MIME_TYPE; invalidate(); } } ManifestEntry setThisMF(Manifest thisMF) { this.thisMF = thisMF; return this; } @Override public String toString() { return "ManifestEntry{" + "path='" + path + '\'' + ", hash='" + hash + '\'' + ", contentType='" + contentType + '\'' + ", status=" + status + '}'; } } public final static String MANIFEST_MIME_TYPE = "application/bzz-manifest+json"; private DPA dpa; private final StringTrie<ManifestEntry> trie; /** * Constructs the Manifest instance with backing DPA storage * @param dpa DPA */ public Manifest(DPA dpa) { this(dpa, new ManifestEntry(null, "")); } private Manifest(DPA dpa, ManifestEntry root) { this.dpa = dpa; trie = new StringTrie<ManifestEntry>(root.setThisMF(this)) {}; } /** * Retrieves the entry with the specified path loading necessary nested manifests on demand */ public ManifestEntry get(String path) { return trie.get(path); } /** * Adds a new entry to the manifest hierarchy with loading necessary nested manifests on demand. * The entry path should contain the absolute path relative to this manifest root */ public void add(ManifestEntry entry) { add(null, entry); } void add(ManifestEntry parent, ManifestEntry entry) { ManifestEntry added = parent == null ? trie.add(entry.path) : trie.add(parent, entry.path); added.hash = entry.hash; added.contentType = entry.contentType; added.status = entry.status; } /** * Deletes the leaf manifest entry with the specified path */ public void delete(String path) { trie.delete(path); } /** * Loads the manifest with the specified hashKey from the DPA storage */ public static Manifest loadManifest(DPA dpa, String hashKey) { ManifestRoot manifestRoot = load(dpa, hashKey); Manifest ret = new Manifest(dpa); for (Manifest.ManifestEntry entry : manifestRoot.entries) { ret.add(entry); } return ret; } private static Manifest.ManifestRoot load(DPA dpa, String hashKey) { try { SectionReader sr = dpa.retrieve(new Key(hashKey)); ObjectMapper om = new ObjectMapper(); String s = Util.readerToString(sr); ManifestRoot manifestRoot = om.readValue(s, ManifestRoot.class); return manifestRoot; } catch (IOException e) { throw new RuntimeException(e); } } /** * Saves this manifest (all its modified nodes) to this manifest DPA storage * @return hashKey of the saved Manifest */ public String save() { return save(trie.rootNode); } private String save(ManifestEntry e) { if (e.isValid()) return e.hash; for (ManifestEntry c : e.getChildren()) { save(c); } e.hash = serialize(dpa, e); return e.hash; } private String serialize(DPA dpa, ManifestEntry manifest) { try { ObjectMapper om = new ObjectMapper(); ManifestRoot mr = new ManifestRoot(manifest); String s = om.writeValueAsString(mr); String hash = dpa.store(Util.stringToReader(s)).getHexString(); return hash; } catch (Exception e) { throw new RuntimeException(e); } } /** * @return manifest dump for debug purposes */ public String dump() { return Util.dumpTree(trie.rootNode); } }
8,198
29.366667
101
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/net/swarm/MemStore.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.apache.commons.collections4.map.AbstractLinkedMap; import org.apache.commons.collections4.map.LRUMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Limited capacity memory storage. Last recently used chunks are purged when * max memory threshold is reached. * * Created by Anton Nashatyrev on 18.06.2015. */ public class MemStore implements ChunkStore { public final Statter statCurSize = Statter.create("net.swarm.memstore.curSize"); public final Statter statCurChunks = Statter.create("net.swarm.memstore.curChunkCnt"); long maxSizeBytes = 10 * 1000000; long curSizeBytes = 0; public MemStore() { } public MemStore(long maxSizeBytes) { this.maxSizeBytes = maxSizeBytes; } // TODO: SoftReference for Chunks? public Map<Key, Chunk> store = Collections.synchronizedMap(new LRUMap<Key, Chunk>(10000) { @Override protected boolean removeLRU(LinkEntry<Key, Chunk> entry) { curSizeBytes -= entry.getValue().getData().length; boolean ret = super.removeLRU(entry); statCurSize.add(curSizeBytes); statCurChunks.add(size()); return ret; } @Override public Chunk put(Key key, Chunk value) { curSizeBytes += value.getData().length; Chunk ret = super.put(key, value); statCurSize.add(curSizeBytes); statCurChunks.add(size()); return ret; } @Override public boolean isFull() { return curSizeBytes >= maxSizeBytes; } }); @Override public void put(Chunk chunk) { store.put(chunk.getKey(), chunk); } @Override public Chunk get(Key key) { return store.get(key); } public void clear() { store.clear(); } }
2,688
29.908046
94
java