org.ethereum.util.ByteUtil Java Examples

The following examples show how to use org.ethereum.util.ByteUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CallCreate.java    From ethereumj with MIT License 6 votes vote down vote up
public CallCreate(JSONObject callCreateJSON) {

        String data        = callCreateJSON.get("data").toString();
        String destination = callCreateJSON.get("destination").toString();
        String gasLimit    = callCreateJSON.get("gasLimit").toString();
        String value       = callCreateJSON.get("value").toString();

        if (data != null && data.length() > 2)
            this.data    = Hex.decode(data.substring(2));
        else
            this.data = ByteUtil.EMPTY_BYTE_ARRAY;

        this.destination = Hex.decode(destination);
        this.gasLimit    = ByteUtil.bigIntegerToBytes(new BigInteger(gasLimit));
        this.value       = ByteUtil.bigIntegerToBytes(new BigInteger(value));
    }
 
Example #2
Source File: DataWord.java    From nuls with MIT License 6 votes vote down vote up
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)));
    }
}
 
Example #3
Source File: Block.java    From ethereumj with MIT License 6 votes vote down vote up
public String toStylishString(){

        if (!parsed) parseRLP();

        toStringBuff.setLength(0);
        toStringBuff.append("<font color=\"${header_color}\"> BlockData </font> [");
        toStringBuff.append("<font color=\"${attribute_color}\">hash</font>=" +
                ByteUtil.toHexString(this.getHash())).append("<br/>");
        toStringBuff.append(header.toStylishString());

        for (TransactionReceipt tx : getTxReceiptList()) {
            toStringBuff.append("<br/>");
            toStringBuff.append(tx.toStylishString());
            toStringBuff.append("<br/>");
        }

        toStringBuff.append("]");
        return toStringBuff.toString();

    }
 
Example #4
Source File: VMTest.java    From ethereumj with MIT License 6 votes vote down vote up
/**
   * Generic test function for SWAP1-16
   * 
   * @param n in SWAPn
   */
  private void testSWAPN_1(int n) {

      VM vm = new VM();
      byte operation = (byte) (OpCode.SWAP1.val() + n - 1);
      String[] expected = new String[n + 1];
      String programCode = "";
      for (int i = 0; i < expected.length; i++) {
      	programCode += "60" + (11+i);
      	expected[i] = "00000000000000000000000000000000000000000000000000000000000000" + (11+i);
}
      program =  new Program(ByteUtil.appendByte(Hex.decode(programCode), operation), invoke);

for (int i = 0; i <= expected.length; i++) {
	vm.step(program);
}

assertEquals(expected.length, program.stack.toArray().length);
assertEquals(expected[0], Hex.toHexString(program.stackPop().getData()).toUpperCase());
for (int i = expected.length-2; i > 0; i--) {
	assertEquals(expected[i], Hex.toHexString(program.stackPop().getData()).toUpperCase());
}
assertEquals(expected[expected.length-1], Hex.toHexString(program.stackPop().getData()).toUpperCase());
  }
 
Example #5
Source File: Block.java    From ethereumj with MIT License 6 votes vote down vote up
public String toFlatString() {
    if (!parsed) parseRLP();

    toStringBuff.setLength(0);
    toStringBuff.append("BlockData [");
    toStringBuff.append("hash=" + ByteUtil.toHexString(this.getHash())).append("");
    toStringBuff.append(header.toFlatString());
    
    for (Transaction tx : getTransactionsList()) {
        toStringBuff.append("\n");
        toStringBuff.append(tx.toString());
    }

    toStringBuff.append("]");
    return toStringBuff.toString();
}
 
Example #6
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
public String toString(int maxDataSize) {
    if(!this.parsed) {
        this.rlpParse();
    }

    String dataS;
    if(this.data == null) {
        dataS = "";
    } else if(this.data.length < maxDataSize) {
        dataS = ByteUtil.toHexString(this.data);
    } else {
        dataS = ByteUtil.toHexString(Arrays.copyOfRange(this.data, 0, maxDataSize)) + "... (" + this.data.length + " bytes)";
    }

    return "TransactionData [hash=" + ByteUtil.toHexString(this.hash) + "  nonce=" + ByteUtil.toHexString(this.nonce) + ", gasPrice=" + ByteUtil.toHexString(this.gasPrice) + ", gas=" + ByteUtil.toHexString(this.gasLimit) + ", receiveAddress=" + ByteUtil.toHexString(this.receiveAddress) + ", value=" + ByteUtil.toHexString(this.value) + ", data=" + dataS + ", signatureV=" + (this.signature == null?"":Byte.valueOf(this.signature.v)) + ", signatureR=" + (this.signature == null?"":ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(this.signature.r))) + ", signatureS=" + (this.signature == null?"":ByteUtil.toHexString(BigIntegers.asUnsignedByteArray(this.signature.s))) + "]";
}
 
Example #7
Source File: EthereumImpl.java    From ethereumj with MIT License 6 votes vote down vote up
@Override
public Transaction createTransaction(BigInteger nonce,
                                     BigInteger gasPrice,
                                     BigInteger gas,
                                     byte[] recieveAddress,
                                     BigInteger value, byte[] data ){

    byte[] nonceBytes    =  ByteUtil.bigIntegerToBytes(nonce);
    byte[] gasPriceBytes =  ByteUtil.bigIntegerToBytes(gasPrice);
    byte[] gasBytes      =  ByteUtil.bigIntegerToBytes(gas);
    byte[] valueBytes    =  ByteUtil.bigIntegerToBytes(value);

    Transaction tx = new Transaction(nonceBytes, gasPriceBytes, gasBytes,
            recieveAddress, valueBytes, data);

    return tx;
}
 
Example #8
Source File: TransactionsMessageTest.java    From ethereumj with MIT License 5 votes vote down vote up
@Test  /* Transactions message 1 */
  public void test_1() {

      String txsPacketRaw = "f86e12f86b04648609184e72a00094cd2a3d9f938e13cd947ec05abc7fe734df8dd826"
      		+ "881bc16d674ec80000801ba05c89ebf2b77eeab88251e553f6f9d53badc1d800"
      		+ "bbac02d830801c2aa94a4c9fa00b7907532b1f29c79942b75fff98822293bf5f"
      		+ "daa3653a8d9f424c6a3265f06c";
      
      byte[] payload = Hex.decode(txsPacketRaw);

      TransactionsMessage transactionsMessage = new TransactionsMessage(payload);
      System.out.println(transactionsMessage);

      assertEquals(EthMessageCodes.TRANSACTIONS, transactionsMessage.getCommand());
      assertEquals(1, transactionsMessage.getTransactions().size());

Transaction tx = transactionsMessage.getTransactions().iterator().next();

assertEquals("5d2aee0490a9228024158433d650335116b4af5a30b8abb10e9b7f9f7e090fd8", Hex.toHexString(tx.getHash()));
assertEquals("04", Hex.toHexString(tx.getNonce()));
assertEquals("1bc16d674ec80000", Hex.toHexString(tx.getValue()));
assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(tx.getReceiveAddress()));
assertEquals("64", Hex.toHexString(tx.getGasPrice()));
assertEquals("09184e72a000", Hex.toHexString(tx.getGasLimit()));
assertEquals("", ByteUtil.toHexString(tx.getData()));

assertEquals("1b", Hex.toHexString(new byte[] { tx.getSignature().v }));
assertEquals("5c89ebf2b77eeab88251e553f6f9d53badc1d800bbac02d830801c2aa94a4c9f", Hex.toHexString(tx.getSignature().r.toByteArray()));
assertEquals("0b7907532b1f29c79942b75fff98822293bf5fdaa3653a8d9f424c6a3265f06c", Hex.toHexString(tx.getSignature().s.toByteArray()));
  }
 
Example #9
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 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)));
}
 
Example #10
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 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)));
}
 
Example #11
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 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)));
}
 
Example #12
Source File: DataSourceArray.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized V set(int idx, V value) {
    if (idx >= size()) {
        setSize(idx + 1);
    }
    src.put(ByteUtil.intToBytes(idx), value);
    return value;
}
 
Example #13
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
public int bytesOccupied() {
    int firstNonZero = ByteUtil.firstNonZeroByte(data);
    if (firstNonZero == -1) {
        return 0;
    }
    return 31 - firstNonZero + 1;
}
 
Example #14
Source File: SystemProperties.java    From nuls with MIT License 5 votes vote down vote up
@ValidateMe
public byte[] getMinerCoinbase() {
    String sc = config.getString("mine.coinbase");
    byte[] c = ByteUtil.hexStringToBytes(sc);
    if (c.length != 20) {
        throw new RuntimeException("mine.coinbase has invalid value: '" + sc + "'");
    }
    return c;
}
 
Example #15
Source File: DataWord.java    From ethereumj with MIT License 5 votes vote down vote up
public DataWord(byte[] data) {
	if (data == null)
		this.data = ByteUtil.EMPTY_BYTE_ARRAY;
	else if (data.length <= 32)
		System.arraycopy(data, 0, this.data, 32 - data.length, data.length);
	else
		throw new RuntimeException("Data word can't exit 32 bytes: " + data);        	
}
 
Example #16
Source File: DataWord.java    From ethereumj with MIT License 5 votes vote down vote up
public void div(DataWord word)  {

        if (word.isZero()) {
            this.and(ZERO);
            return;
        }

		BigInteger result = value().divide(word.value());
		this.data = ByteUtil.copyToArray(result.and(MAX_VALUE));
    }
 
Example #17
Source File: DataWord.java    From ethereumj with MIT License 5 votes vote down vote up
public void sDiv(DataWord word) {

        if (word.isZero()) {
            this.and(ZERO);
            return;
        }

		BigInteger result = sValue().divide(word.sValue());
        this.data = ByteUtil.copyToArray(result.and(MAX_VALUE));
    }
 
Example #18
Source File: DataWord.java    From ethereumj with MIT License 5 votes vote down vote up
public void mod(DataWord word) {

        if (word.isZero()) {
            this.and(ZERO);
            return;
        }

        BigInteger result = value().mod(word.value());
        this.data = ByteUtil.copyToArray(result.and(MAX_VALUE));
    }
 
Example #19
Source File: JSONHelper.java    From ethereumj with MIT License 5 votes vote down vote up
public static void dumpBlock(ObjectNode blockNode, Block block,
			long gasUsed, byte[] state, List<ByteArrayWrapper> keys,
			Repository repository) {
    	
    	blockNode.put("coinbase", Hex.toHexString(block.getCoinbase()));
    	blockNode.put("difficulty", new BigInteger(1, block.calcDifficulty()).toString());
    	blockNode.put("extra_data", "0x");
    	blockNode.put("gas_limit", String.valueOf(block.calcGasLimit()));
    	blockNode.put("gas_used", String.valueOf(gasUsed));
    	blockNode.put("min_gas_price", String.valueOf(block.getMinGasPrice()));
    	blockNode.put("nonce", "0x" + Hex.toHexString(block.getNonce()));
    	blockNode.put("number", String.valueOf(block.getNumber()));
    	blockNode.put("prevhash", "0x" + Hex.toHexString(block.getParentHash()));
        
        ObjectNode statesNode = blockNode.objectNode();
        for (ByteArrayWrapper key : keys) {
            byte[] keyBytes = key.getData();
            AccountState    accountState    = repository.getAccountState(keyBytes);
            ContractDetails details  = repository.getContractDetails(keyBytes);
            JSONHelper.dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details);
        }       
        blockNode.put("state", statesNode);
        
        blockNode.put("state_root", Hex.toHexString(state));
        blockNode.put("timestamp", String.valueOf(block.getTimestamp()));
        
        ArrayNode transactionsNode = blockNode.arrayNode();
        blockNode.put("transactions", transactionsNode);
        
        blockNode.put("tx_list_root", ByteUtil.toHexString(block.getTxTrieRoot()));
        blockNode.put("uncles_hash", "0x" + Hex.toHexString(block.getUnclesHash()));
        
//		JSONHelper.dumpTransactions(blockNode,
//				stateRoot, codeHash, code, storage);
    }
 
Example #20
Source File: DataSourceArray.java    From nuls with MIT License 5 votes vote down vote up
@Override
public synchronized int size() {
    if (size < 0) {
        byte[] sizeBB = src.getSource().get(SIZE_KEY);
        size = sizeBB == null ? 0 : ByteUtil.byteArrayToInt(sizeBB);
    }
    return size;
}
 
Example #21
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
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)));
    }
 
Example #22
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
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)));
}
 
Example #23
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
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)));
    }
 
Example #24
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
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)));
    }
 
Example #25
Source File: TrieImpl.java    From ethereumj with MIT License 5 votes vote down vote up
@Override
public byte[] getRootHash() {
    if (root == null
            || (root instanceof byte[] && ((byte[]) root).length == 0)
            || (root instanceof String && "".equals((String) root))) {
        return ByteUtil.EMPTY_BYTE_ARRAY;
    } else if (root instanceof byte[]) {
        return (byte[]) this.getRoot();
    } else {
        Value rootValue = new Value(this.getRoot());
        byte[] val = rootValue.encode();
        return HashUtil.sha3(val);
    }
}
 
Example #26
Source File: DataWord.java    From nuls with MIT License 5 votes vote down vote up
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)));
    }
 
Example #27
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public byte[] getEncoded() {
    if(this.rlpEncoded != null) {
        return this.rlpEncoded;
    } else {
        byte[] nonce = null;
        if(this.nonce != null && (this.nonce.length != 1 || this.nonce[0] != 0)) {
            nonce = RLP.encodeElement(this.nonce);
        } else {
            nonce = RLP.encodeElement((byte[])null);
        }

        byte[] gasPrice = RLP.encodeElement(this.gasPrice);
        byte[] gasLimit = RLP.encodeElement(this.gasLimit);
        byte[] receiveAddress = RLP.encodeElement(this.receiveAddress);
        byte[] value = RLP.encodeElement(this.value);
        byte[] data = RLP.encodeElement(this.data);
        byte[] v;
        byte[] r;
        byte[] s;
        if(this.signature != null) {
            v = RLP.encodeByte(this.signature.v);
            r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(this.signature.r));
            s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(this.signature.s));
        } else {
            v = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
            r = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
            s = RLP.encodeElement(ByteUtil.EMPTY_BYTE_ARRAY);
        }

        this.rlpEncoded = RLP.encodeList(new byte[][]{nonce, gasPrice, gasLimit, receiveAddress, value, data, v, r, s});
        this.hash = this.getHash();
        return this.rlpEncoded;
    }
}
 
Example #28
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public boolean isContractCreation() {
    if(!this.parsed) {
        this.rlpParse();
    }

    return this.receiveAddress == null || Arrays.equals(this.receiveAddress, ByteUtil.EMPTY_BYTE_ARRAY);
}
 
Example #29
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public byte[] getGasPrice() {
    if(!this.parsed) {
        this.rlpParse();
    }

    return this.gasPrice == null?ByteUtil.ZERO_BYTE_ARRAY:this.gasPrice;
}
 
Example #30
Source File: Transaction.java    From wkcwallet-java with Apache License 2.0 5 votes vote down vote up
public byte[] getValue() {
    if(!this.parsed) {
        this.rlpParse();
    }

    return this.value == null?ByteUtil.ZERO_BYTE_ARRAY:this.value;
}