Java Code Examples for org.web3j.utils.Numeric#cleanHexPrefix()

The following examples show how to use org.web3j.utils.Numeric#cleanHexPrefix() . 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: Contract.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check that the contract deployed at the address associated with this smart contract wrapper
 * is in fact the contract you believe it is.
 *
 * <p>This method uses the
 * <a href="https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method
 * to get the contract byte code and validates it against the byte code stored in this smart
 * contract wrapper.
 *
 * @return true if the contract is valid
 * @throws IOException if unable to connect to web3j node
 */
public boolean isValid() throws IOException {
    if (contractAddress.equals("")) {
        throw new UnsupportedOperationException(
                "Contract binary not present, you will need to regenerate your smart "
                        + "contract wrapper with web3j v2.2.0+");
    }

    EthGetCode ethGetCode = web3j
            .ethGetCode(contractAddress, DefaultBlockParameterName.LATEST)
            .send();
    if (ethGetCode.hasError()) {
        return false;
    }

    String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
    // There may be multiple contracts in the Solidity bytecode, hence we only check for a
    // match with a subset
    return !code.isEmpty() && contractBinary.contains(code);
}
 
Example 2
Source File: DefaultFunctionReturnDecoder.java    From web3j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends Type> Type decodeEventParameter(
        String rawInput, TypeReference<T> typeReference) {

    String input = Numeric.cleanHexPrefix(rawInput);

    try {
        Class<T> type = typeReference.getClassType();

        if (Bytes.class.isAssignableFrom(type)) {
            Class<Bytes> bytesClass = (Class<Bytes>) Class.forName(type.getName());
            return TypeDecoder.decodeBytes(input, bytesClass);
        } else if (Array.class.isAssignableFrom(type)
                || BytesType.class.isAssignableFrom(type)
                || Utf8String.class.isAssignableFrom(type)) {
            return TypeDecoder.decodeBytes(input, Bytes32.class);
        } else {
            return TypeDecoder.decode(input, type);
        }
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Invalid class reference provided", e);
    }
}
 
Example 3
Source File: Keys.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checksum address encoding as per
 * <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md">EIP-55</a>.
 *
 * @param address a valid hex encoded address
 * @return hex encoded checksum address
 */
public static String toChecksumAddress(String address) {
    String lowercaseAddress = Numeric.cleanHexPrefix(address).toLowerCase();
    String addressHash = Numeric.cleanHexPrefix(Hash.sha3String(lowercaseAddress));

    StringBuilder result = new StringBuilder(lowercaseAddress.length() + 2);

    result.append("0x");

    for (int i = 0; i < lowercaseAddress.length(); i++) {
        if (Integer.parseInt(String.valueOf(addressHash.charAt(i)), 16) >= 8) {
            result.append(String.valueOf(lowercaseAddress.charAt(i)).toUpperCase());
        } else {
            result.append(lowercaseAddress.charAt(i));
        }
    }

    return result.toString();
}
 
Example 4
Source File: RawTransaction.java    From web3j with Apache License 2.0 6 votes vote down vote up
protected RawTransaction(
        BigInteger nonce,
        BigInteger gasPrice,
        BigInteger gasLimit,
        String to,
        BigInteger value,
        String data,
        BigInteger gasPremium,
        BigInteger feeCap) {
    this.nonce = nonce;
    this.gasPrice = gasPrice;
    this.gasLimit = gasLimit;
    this.to = to;
    this.value = value;
    this.data = data != null ? Numeric.cleanHexPrefix(data) : null;
    this.gasPremium = gasPremium;
    this.feeCap = feeCap;
}
 
Example 5
Source File: BaseContract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private <T> CallResponse<List<T>> executeCallListValueReturn(Function function, Class<T> returnType) throws IOException {
	PlatonCall ethCall = web3j.platonCall(
            Transaction.createEthCallTransaction(
            		transactionManager.getFromAddress(), contractAddress, EncoderUtils.functionEncoder(function)),
            DefaultBlockParameterName.LATEST)
            .send();
	
	String result = Numeric.cleanHexPrefix(ethCall.getValue());
	if(result==null || "".equals(result)){
		  throw new ContractCallException("Empty value (0x) returned from contract");
	}
	
	CallRet callRet = JSONUtil.parseObject(new String(Hex.decode(result)), CallRet.class);
    if (callRet == null) {
    	throw new ContractCallException("Unable to convert response: " + result);
    }
    
    CallResponse<List<T>> callResponse = new CallResponse<List<T>>();
    if (callRet.isStatusOk()) {
    	callResponse.setCode(callRet.getCode());
    	callResponse.setData(JSONUtil.parseArray(JSONUtil.toJSONString(callRet.getRet()), returnType));
    } else {
    	callResponse.setCode(callRet.getCode());
    	callResponse.setErrMsg(callRet.getRet().toString());
    }

    if(callRet.getCode() == ErrorCode.OBJECT_NOT_FOUND){
        callResponse.setCode(ErrorCode.SUCCESS);
        callResponse.setData(Collections.emptyList());
    }

    return callResponse;
}
 
Example 6
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
/**
 * Reverse name resolution as documented in the <a
 * href="https://docs.ens.domains/contract-api-reference/reverseregistrar">specification</a>.
 *
 * @param address an ethereum address, example: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"
 * @return a EnsName registered for provided address
 */
public String reverseResolve(String address) throws UnableToResolveENS
{
    String name = null;
    if (WalletUtils.isValidAddress(address))
    {
        String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
        try
        {
            String resolverAddress = lookupResolver(reverseName);
            byte[] nameHash = NameHash.nameHashAsBytes(reverseName);
            name = getContractData(EthereumNetworkBase.MAINNET_ID, resolverAddress, getName(nameHash));
        }
        catch (Exception e)
        {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!isValidEnsName(name, addressLength))
        {
            throw new UnableToResolveENS("Unable to resolve name for address: " + address);
        }
        else
        {
            return name;
        }
    }
    else
    {
        throw new EnsResolutionException("Address is invalid: " + address);
    }
}
 
Example 7
Source File: WalletUtils.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidAddress(String input) {
    String cleanInput = Numeric.cleanHexPrefix(input);

    try {
        Numeric.toBigIntNoPrefix(cleanInput);
    } catch (NumberFormatException e) {
        return false;
    }

    return cleanInput.length() == ADDRESS_LENGTH_IN_HEX;
}
 
Example 8
Source File: Contract.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the contract deployed at the address associated with this smart contract wrapper
 * is in fact the contract you believe it is.
 *
 * <p>This method uses the <a
 * href="https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method to
 * get the contract byte code and validates it against the byte code stored in this smart
 * contract wrapper.
 *
 * @return true if the contract is valid
 * @throws IOException if unable to connect to web3j node
 */
public boolean isValid() throws IOException {
    if (contractBinary.equals(BIN_NOT_PROVIDED)) {
        throw new UnsupportedOperationException(
                "Contract binary not present in contract wrapper, "
                        + "please generate your wrapper using -abiFile=<file>");
    }

    if (contractAddress.equals("")) {
        throw new UnsupportedOperationException(
                "Contract binary not present, you will need to regenerate your smart "
                        + "contract wrapper with web3j v2.2.0+");
    }

    EthGetCode ethGetCode =
            transactionManager.getCode(contractAddress, DefaultBlockParameterName.LATEST);
    if (ethGetCode.hasError()) {
        return false;
    }

    String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
    int metadataIndex = code.indexOf("a165627a7a72305820");
    if (metadataIndex != -1) {
        code = code.substring(0, metadataIndex);
    }
    // There may be multiple contracts in the Solidity bytecode, hence we only check for a
    // match with a subset
    return !code.isEmpty() && contractBinary.contains(code);
}
 
Example 9
Source File: RawTransaction.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
protected RawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to,
                       BigInteger value, String data) {
    this.nonce = nonce;
    this.gasPrice = gasPrice;
    this.gasLimit = gasLimit;
    this.to = to;
    this.value = value;

    if (data != null) {
        this.data = Numeric.cleanHexPrefix(data);
    }
}
 
Example 10
Source File: FunctionReturnDecoder.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decode ABI encoded return values from smart contract function call.
 *
 * @param rawInput ABI encoded input
 * @param outputParameters list of return types as {@link TypeReference}
 * @return {@link List} of values returned by function, {@link Collections#emptyList()} if
 *         invalid response
 */
public static List<Type> decode(
        String rawInput, List<TypeReference<Type>> outputParameters) {
    String input = Numeric.cleanHexPrefix(rawInput);

    if (Strings.isEmpty(input)) {
        return Collections.emptyList();
    } else {
        return build(input, outputParameters);
    }
}
 
Example 11
Source File: BaseContract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private <T> CallResponse<T> executeCallObjectValueReturn(Function function, Class<T> returnType) throws IOException {
 	PlatonCall ethCall = web3j.platonCall(
             Transaction.createEthCallTransaction(
             		transactionManager.getFromAddress(), contractAddress, EncoderUtils.functionEncoder(function)),
             DefaultBlockParameterName.LATEST)
             .send();
 	
 	String result = Numeric.cleanHexPrefix(ethCall.getValue());
 	if(result==null || "".equals(result)){
 		  throw new ContractCallException("Empty value (0x) returned from contract");
 	}

 	CallRet callRet = JSONUtil.parseObject(new String(Hex.decode(result)), CallRet.class);
     if (callRet == null) {
     	throw new ContractCallException("Unable to convert response: " + result);
     }
     
     CallResponse<T> callResponse = new CallResponse<T>();
     if (callRet.isStatusOk()) {
     	callResponse.setCode(callRet.getCode());
     	if(BigInteger.class.isAssignableFrom(returnType) ) {
     		callResponse.setData((T)numberDecoder(callRet.getRet()));
     	}else {
     		callResponse.setData(JSONUtil.parseObject(JSONUtil.toJSONString(callRet.getRet()), returnType));
}
     } else {
     	callResponse.setCode(callRet.getCode());
     	callResponse.setErrMsg(callRet.getRet().toString());
     }
     return callResponse;
 }
 
Example 12
Source File: Keys.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static String getAddress(String publicKey) {
    String publicKeyNoPrefix = Numeric.cleanHexPrefix(publicKey);

    if (publicKeyNoPrefix.length() < PUBLIC_KEY_LENGTH_IN_HEX) {
        publicKeyNoPrefix =
                Strings.zeros(PUBLIC_KEY_LENGTH_IN_HEX - publicKeyNoPrefix.length())
                        + publicKeyNoPrefix;
    }
    String hash = Hash.sha3(publicKeyNoPrefix);
    return hash.substring(hash.length() - ADDRESS_LENGTH_IN_HEX); // right most 160 bits
}
 
Example 13
Source File: KeystoreAccountService.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private String extractAddressFromStore(String store) throws Exception {
    try {
        JSONObject jsonObject = new JSONObject(store);
        return "0x" + Numeric.cleanHexPrefix(jsonObject.getString("address"));
    } catch (JSONException ex) {
        throw new Exception("Invalid keystore");
    }
}
 
Example 14
Source File: RawTransaction.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
protected RawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to,
                       BigInteger value, String data) {
    this.nonce = nonce;
    this.gasPrice = gasPrice;
    this.gasLimit = gasLimit;
    this.to = to;
    this.value = value;

    if (data != null) {
        this.data = Numeric.cleanHexPrefix(data);
    }
}
 
Example 15
Source File: WalletUtils.java    From web3j with Apache License 2.0 4 votes vote down vote up
public static boolean isValidPrivateKey(String privateKey) {
    String cleanPrivateKey = Numeric.cleanHexPrefix(privateKey);
    return cleanPrivateKey.length() == PRIVATE_KEY_LENGTH_IN_HEX;
}
 
Example 16
Source File: TransactionDecoder.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public ContractType getContractType(String input)
{
    if (input.length() < 10) return ContractType.OTHER;
    Map<ContractType, Integer> functionCount = new HashMap<>();
    ContractType highestType = ContractType.OTHER;
    int highestCount = 0;

    //improve heuristic:
    String balanceMethod = Numeric.cleanHexPrefix(buildMethodId("balanceOf(address)"));
    String isStormbird = Numeric.cleanHexPrefix(buildMethodId("isStormBirdContract()"));
    String isStormbird2 = Numeric.cleanHexPrefix(buildMethodId("isStormBird()"));
    String trade = Numeric.cleanHexPrefix(buildMethodId("trade(uint256,uint256[],uint8,bytes32,bytes32)"));
    String tradeLegacy = Numeric.cleanHexPrefix(buildMethodId("trade(uint256,uint16[],uint8,bytes32,bytes32)"));

    if (input.contains(balanceMethod))
    {
        if (input.contains(isStormbird) || input.contains(isStormbird2) || input.contains(tradeLegacy) || input.contains(trade))
        {
            if (input.contains(tradeLegacy))
            {
                return ContractType.ERC875_LEGACY;
            }
            else
            {
                return ContractType.ERC875;
            }
        }
    }
    else
    {
        return ContractType.OTHER;
    }

    //ERC721/x or ERC20

    for (String signature : functionList.keySet())
    {
        String cleanSig = Numeric.cleanHexPrefix(signature);
        int index = input.indexOf(cleanSig);
        if (index >= 0)
        {
            FunctionData data = functionList.get(signature);
            for (ContractType type : data.contractType)
            {
                int count = 0;
                if (functionCount.containsKey(type)) count = functionCount.get(type);
                count++;
                functionCount.put(type, count);
                if (count > highestCount)
                {
                    highestCount = count;
                    highestType = type;
                }
            }
        }
    }

    if (highestType == ContractType.ERC721 && functionCount.containsKey(ContractType.ERC721_LEGACY))
    {
        highestType = ContractType.ERC721_LEGACY;
    }
    else if (functionCount.containsKey(ContractType.ERC20))
    {
        highestType = ContractType.ERC20;
    }

    return highestType;
}
 
Example 17
Source File: WalletUtils.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
public static boolean isValidPrivateKey(String privateKey) {
    String cleanPrivateKey = Numeric.cleanHexPrefix(privateKey);
    return cleanPrivateKey.length() == PRIVATE_KEY_LENGTH_IN_HEX;
}
 
Example 18
Source File: Token.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
public boolean addressMatches(String contractAddress)
{
    String checkAddress = Numeric.cleanHexPrefix(contractAddress);
    String ourAddress = Numeric.cleanHexPrefix(getAddress());
    return ourAddress.equalsIgnoreCase(checkAddress);
}
 
Example 19
Source File: FunctionReturnDecoder.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Decodes an indexed parameter associated with an event. Indexed parameters are individually
 * encoded, unlike non-indexed parameters which are encoded as per ABI-encoded function
 * parameters and return values.</p>
 *
 * <p>If any of the following types are indexed, the Keccak-256 hashes of the values are
 * returned instead. These are returned as a bytes32 value.</p>
 *
 * <ul>
 *     <li>Arrays</li>
 *     <li>Strings</li>
 *     <li>Bytes</li>
 * </ul>
 *
 * <p>See the
 * <a href="http://solidity.readthedocs.io/en/latest/contracts.html#events">
 * Solidity documentation</a> for further information.</p>
 *
 * @param rawInput ABI encoded input
 * @param typeReference of expected result type
 * @param <T> type of TypeReference
 * @return the decode value
 */
@SuppressWarnings("unchecked")
public static <T extends Type> Type decodeIndexedValue(
        String rawInput, TypeReference<T> typeReference) {
    String input = Numeric.cleanHexPrefix(rawInput);

    try {
        Class<T> type = typeReference.getClassType();

        if (Bytes.class.isAssignableFrom(type)) {
            return TypeDecoder.decodeBytes(input, (Class<Bytes>) Class.forName(type.getName()));
        } else if (Array.class.isAssignableFrom(type)
                || BytesType.class.isAssignableFrom(type)
                || Utf8String.class.isAssignableFrom(type)) {
            return TypeDecoder.decodeBytes(input, Bytes32.class);
        } else {
            return TypeDecoder.decode(input, type);
        }
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Invalid class reference provided", e);
    }
}
 
Example 20
Source File: FunctionReturnDecoder.java    From etherscan-explorer with GNU General Public License v3.0 3 votes vote down vote up
/**
 * <p>Decodes an indexed parameter associated with an event. Indexed parameters are individually
 * encoded, unlike non-indexed parameters which are encoded as per ABI-encoded function
 * parameters and return values.</p>
 *
 * <p>If any of the following types are indexed, the Keccak-256 hashes of the values are
 * returned instead. These are returned as a bytes32 value.</p>
 *
 * <ul>
 *     <li>Arrays</li>
 *     <li>Strings</li>
 *     <li>Bytes</li>
 * </ul>
 *
 * <p>See the
 * <a href="http://solidity.readthedocs.io/en/latest/contracts.html#events">
 * Solidity documentation</a> for further information.</p>
 *
 * @param rawInput ABI encoded input
 * @param typeReference of expected result type
 * @param <T> type of TypeReference
 * @return the decode value
 */
@SuppressWarnings("unchecked")
public static <T extends Type> Type decodeIndexedValue(
        String rawInput, TypeReference<T> typeReference) {
    String input = Numeric.cleanHexPrefix(rawInput);

    try {
        Class<T> type = typeReference.getClassType();

        if (Bytes.class.isAssignableFrom(type)) {
            return TypeDecoder.decodeBytes(input, (Class<Bytes>) Class.forName(type.getName()));
        } else if (Array.class.isAssignableFrom(type)
                || BytesType.class.isAssignableFrom(type)
                || Utf8String.class.isAssignableFrom(type)) {
            return TypeDecoder.decodeBytes(input, Bytes32.class);
        } else {
            return TypeDecoder.decode(input, type);
        }
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Invalid class reference provided", e);
    }
}