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

The following examples show how to use org.web3j.utils.Numeric#toHexString() . 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: CreateRawTransactionIT.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeploySmartContract() throws Exception {
    BigInteger nonce = getNonce(ALICE.getAddress());
    RawTransaction rawTransaction = createSmartContractTransaction(nonce);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ALICE);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction ethSendTransaction =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();
    String transactionHash = ethSendTransaction.getTransactionHash();

    assertFalse(transactionHash.isEmpty());

    TransactionReceipt transactionReceipt = waitForTransactionReceipt(transactionHash);

    assertEquals(transactionHash, transactionReceipt.getTransactionHash());

    assertFalse(
            rawTransaction.getGasLimit().equals(transactionReceipt.getGasUsed()),
            "Contract execution ran out of gas");
}
 
Example 2
Source File: HumanStandardTokenIT.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String execute(
        Credentials credentials, Function function, String contractAddress) throws Exception {
    BigInteger nonce = getNonce(credentials.getAddress());

    String encodedFunction = FunctionEncoder.encode(function);

    RawTransaction rawTransaction = RawTransaction.createTransaction(
            nonce,
            GAS_PRICE,
            GAS_LIMIT,
            contractAddress,
            encodedFunction);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction transactionResponse = web3j.ethSendRawTransaction(hexValue)
            .sendAsync().get();

    return transactionResponse.getTransactionHash();
}
 
Example 3
Source File: CreateRawTransactionIT.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDeploySmartContract() throws Exception {
    BigInteger nonce = getNonce(ALICE.getAddress());
    RawTransaction rawTransaction = createSmartContractTransaction(nonce);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, ALICE);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction ethSendTransaction =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();
    String transactionHash = ethSendTransaction.getTransactionHash();

    assertFalse(transactionHash.isEmpty());

    TransactionReceipt transactionReceipt =
            waitForTransactionReceipt(transactionHash);

    assertThat(transactionReceipt.getTransactionHash(), is(transactionHash));

    assertFalse("Contract execution ran out of gas",
            rawTransaction.getGasLimit().equals(transactionReceipt.getGasUsed()));
}
 
Example 4
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 6 votes vote down vote up
private String execute(Credentials credentials, Function function, String contractAddress)
        throws Exception {
    BigInteger nonce = getNonce(credentials.getAddress());

    String encodedFunction = FunctionEncoder.encode(function);

    RawTransaction rawTransaction =
            RawTransaction.createTransaction(
                    nonce, GAS_PRICE, GAS_LIMIT, contractAddress, encodedFunction);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction transactionResponse =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();

    return transactionResponse.getTransactionHash();
}
 
Example 5
Source File: TransactionDecoderTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecoding() throws Exception {
    BigInteger nonce = BigInteger.ZERO;
    BigInteger gasPrice = BigInteger.ONE;
    BigInteger gasLimit = BigInteger.TEN;
    String to = "0x0add5355";
    BigInteger value = BigInteger.valueOf(Long.MAX_VALUE);
    RawTransaction rawTransaction =
            RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, value);
    byte[] encodedMessage = TransactionEncoder.encode(rawTransaction);
    String hexMessage = Numeric.toHexString(encodedMessage);

    RawTransaction result = TransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(nonce, result.getNonce());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals(to, result.getTo());
    assertEquals(value, result.getValue());
    assertEquals("", result.getData());
}
 
Example 6
Source File: EthereumNetworkManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected RawTransactionResponse doInBackground(Void... params) {
    BigInteger nonce = getNonce();
    if (nonce == null) return null;
    RawTransaction rawTransaction;
    String blockNumber = getBlocNumber();
    if (TextUtils.isEmpty(contractData)) {
        rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, value);
    } else {
        rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, toAddress, new String(Hex.encode(contractData.getBytes())));
    }

    byte[] signedMessage;
    if (walletManager.getCredentials() != null && rawTransaction != null) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, walletManager.getCredentials());
    } else {
        return null;
    }

    String hexValue = Numeric.toHexString(signedMessage);
    EthSendTransaction ethSendTransaction = null;


        try {
            ethSendTransaction = web3jConnection.ethSendRawTransaction(hexValue).send();
        } catch (IOException e) {
            e.printStackTrace();
        }

    if (ethSendTransaction != null && ethSendTransaction.getTransactionHash() != null) {
        return new RawTransactionResponse(ethSendTransaction.getTransactionHash(),
                hexValue, blockNumber);
    } else {
        return null;
    }
}
 
Example 7
Source File: PaperWallet.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
public String createOfflineTx(String toAddress, BigInteger gasPrice, BigInteger gasLimit, BigInteger amount, BigInteger nonce) {
	RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, amount);
	byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
	String hexValue = Numeric.toHexString(signedMessage);
	
	return hexValue;
}
 
Example 8
Source File: TransactionEncoderTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignMessage() {
    byte[] signedMessage = TransactionEncoder.signMessage(
            createEtherTransaction(), SampleKeys.CREDENTIALS);
    String hexMessage = Numeric.toHexString(signedMessage);
    assertThat(hexMessage,
            is("0xf85580010a840add5355887fffffffffffffff80"
                    + "1c"
                    + "a046360b50498ddf5566551ce1ce69c46c565f1f478bb0ee680caf31fbc08ab727"
                    + "a01b2f1432de16d110407d544f519fc91b84c8e16d3b6ec899592d486a94974cd0"));
}
 
Example 9
Source File: PrivateTransactionDecoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodingPrivacyGroup() {
    final BigInteger nonce = BigInteger.ZERO;
    final BigInteger gasPrice = BigInteger.ONE;
    final BigInteger gasLimit = BigInteger.TEN;
    final String to = "0x0add5355";
    final RawPrivateTransaction rawTransaction =
            RawPrivateTransaction.createTransaction(
                    nonce,
                    gasPrice,
                    gasLimit,
                    to,
                    "",
                    MOCK_ENCLAVE_KEY,
                    MOCK_ENCLAVE_KEY,
                    RESTRICTED);
    byte[] encodedMessage = PrivateTransactionEncoder.encode(rawTransaction);
    final String hexMessage = Numeric.toHexString(encodedMessage);

    final RawPrivateTransaction result = PrivateTransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(nonce, result.getNonce());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals(to, result.getTo());
    assertEquals("", result.getData());
    assertEquals(MOCK_ENCLAVE_KEY, result.getPrivateFrom());
    assertEquals(MOCK_ENCLAVE_KEY, result.getPrivacyGroupId().get());
    assertEquals(RESTRICTED, result.getRestriction());
}
 
Example 10
Source File: HumanStandardTokenIT.java    From web3j with Apache License 2.0 5 votes vote down vote up
private String sendCreateContractTransaction(Credentials credentials, BigInteger initialSupply)
        throws Exception {
    BigInteger nonce = getNonce(credentials.getAddress());

    String encodedConstructor =
            FunctionEncoder.encodeConstructor(
                    Arrays.asList(
                            new Uint256(initialSupply),
                            new Utf8String("web3j tokens"),
                            new Uint8(BigInteger.TEN),
                            new Utf8String("w3j$")));

    RawTransaction rawTransaction =
            RawTransaction.createContractTransaction(
                    nonce,
                    GAS_PRICE,
                    GAS_LIMIT,
                    BigInteger.ZERO,
                    getHumanStandardTokenBinary() + encodedConstructor);

    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    String hexValue = Numeric.toHexString(signedMessage);

    EthSendTransaction transactionResponse =
            web3j.ethSendRawTransaction(hexValue).sendAsync().get();

    return transactionResponse.getTransactionHash();
}
 
Example 11
Source File: TransactionDecoderTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDecodingSignedChainId() throws Exception {
    BigInteger nonce = BigInteger.ZERO;
    BigInteger gasPrice = BigInteger.ONE;
    BigInteger gasLimit = BigInteger.TEN;
    String to = "0x0add5355";
    BigInteger value = BigInteger.valueOf(Long.MAX_VALUE);
    Integer chainId = 1;
    RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
            nonce, gasPrice, gasLimit, to, value);
    byte[] signedMessage = TransactionEncoder.signMessage(
            rawTransaction, chainId.byteValue(), SampleKeys.CREDENTIALS);
    String hexMessage = Numeric.toHexString(signedMessage);

    RawTransaction result = TransactionDecoder.decode(hexMessage);
    assertNotNull(result);
    assertEquals(nonce, result.getNonce());
    assertEquals(gasPrice, result.getGasPrice());
    assertEquals(gasLimit, result.getGasLimit());
    assertEquals(to, result.getTo());
    assertEquals(value, result.getValue());
    assertEquals("", result.getData());
    assertTrue(result instanceof SignedRawTransaction);
    SignedRawTransaction signedResult = (SignedRawTransaction) result;
    assertEquals(SampleKeys.ADDRESS, signedResult.getFrom());
    signedResult.verify(SampleKeys.ADDRESS);
    assertEquals(chainId, signedResult.getChainId());
}
 
Example 12
Source File: TransactionEncoderTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSignMessage() {
    byte[] signedMessage = TransactionEncoder.signMessage(
            createEtherTransaction(), SampleKeys.CREDENTIALS);
    String hexMessage = Numeric.toHexString(signedMessage);
    assertThat(hexMessage,
            is("0xf85580010a840add5355887fffffffffffffff80"
                    + "1c"
                    + "a046360b50498ddf5566551ce1ce69c46c565f1f478bb0ee680caf31fbc08ab727"
                    + "a01b2f1432de16d110407d544f519fc91b84c8e16d3b6ec899592d486a94974cd0"));
}
 
Example 13
Source File: PrivateTransactionManager.java    From web3j with Apache License 2.0 5 votes vote down vote up
public String sign(RawPrivateTransaction rawTransaction) {

        byte[] signedMessage;

        if (chainId > ChainIdLong.NONE) {
            signedMessage =
                    PrivateTransactionEncoder.signMessage(rawTransaction, chainId, credentials);
        } else {
            signedMessage = PrivateTransactionEncoder.signMessage(rawTransaction, credentials);
        }

        return Numeric.toHexString(signedMessage);
    }
 
Example 14
Source File: NameHash.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
public static String nameHash(String ensName) {
    String normalisedEnsName = normalise(ensName);
    return Numeric.toHexString(nameHash(normalisedEnsName.split("\\.")));
}
 
Example 15
Source File: RlpString.java    From web3j with Apache License 2.0 4 votes vote down vote up
public String asString() {
    return Numeric.toHexString(value);
}
 
Example 16
Source File: TokenscriptFunction.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
private String handleTransactionResult(TransactionResult result, Function function, String responseValue, Attribute attr, long lastTransactionTime)
{
    String transResult = null;
    try
    {
        //try to interpret the value. For now, just use the raw return value - this is more reliable until we need to interpret arrays
        List<Type> response = FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
        if (response.size() > 0)
        {
            result.resultTime = lastTransactionTime;
            Type val = response.get(0);

            BigInteger value;
            byte[] bytes = Bytes.trimLeadingZeroes(Numeric.hexStringToByteArray(responseValue));
            String hexBytes = Numeric.toHexString(bytes);

            switch (attr.syntax)
            {
                case Boolean:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.equals(BigDecimal.ZERO) ? "FALSE" : "TRUE";
                    break;
                case Integer:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.toString();
                    break;
                case BitString:
                case NumericString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else
                    {
                        //should be a decimal string
                        value = Numeric.toBigInt(hexBytes);
                        transResult = value.toString();
                    }
                    break;
                case IA5String:
                case DirectoryString:
                case GeneralizedTime:
                case CountryString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else if (val.getTypeAsString().equals("address"))
                    {
                        transResult = (String)val.getValue();
                    }
                    else
                    {
                        transResult = hexBytes;
                    }
                    break;
                default:
                    transResult = hexBytes;
                    break;
            }
        }
        else
        {
            result.resultTime = lastTransactionTime == -1 ? -1 : 0;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return transResult;
}
 
Example 17
Source File: TokenscriptFunction.java    From alpha-wallet-android with MIT License 4 votes vote down vote up
private String handleTransactionResult(TransactionResult result, Function function, String responseValue, Attribute attr, long lastTransactionTime)
{
    String transResult = null;
    try
    {
        //try to interpret the value. For now, just use the raw return value - this is more reliable until we need to interpret arrays
        List<Type> response = FunctionReturnDecoder.decode(responseValue, function.getOutputParameters());
        if (response.size() > 0)
        {
            result.resultTime = lastTransactionTime;
            Type val = response.get(0);

            BigInteger value;
            byte[] bytes = Bytes.trimLeadingZeroes(Numeric.hexStringToByteArray(responseValue));
            String hexBytes = Numeric.toHexString(bytes);

            switch (attr.syntax)
            {
                case Boolean:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.equals(BigDecimal.ZERO) ? "FALSE" : "TRUE";
                    break;
                case Integer:
                    value = Numeric.toBigInt(hexBytes);
                    transResult = value.toString();
                    break;
                case BitString:
                case NumericString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else
                    {
                        //should be a decimal string
                        value = Numeric.toBigInt(hexBytes);
                        transResult = value.toString();
                    }
                    break;
                case IA5String:
                case DirectoryString:
                case GeneralizedTime:
                case CountryString:
                    if (val.getTypeAsString().equals("string"))
                    {
                        transResult = (String)val.getValue();
                        if (responseValue.length() > 2 && transResult.length() == 0)
                        {
                            transResult = checkBytesString(responseValue);
                        }
                    }
                    else if (val.getTypeAsString().equals("address"))
                    {
                        transResult = (String)val.getValue();
                    }
                    else
                    {
                        transResult = hexBytes;
                    }
                    break;
                default:
                    transResult = hexBytes;
                    break;
            }
        }
        else
        {
            result.resultTime = lastTransactionTime == -1 ? -1 : 0;
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return transResult;
}
 
Example 18
Source File: SupportedSolidityTypesIT.java    From eventeum with Apache License 2.0 3 votes vote down vote up
@Test
public void testBytes16Broadcast() throws Exception {
    final EventEmitter eventEmitter = deployEventEmitterContract();

    final ContractEventSpecification eventSpec = new ContractEventSpecification();
    eventSpec.setIndexedParameterDefinitions(
            Arrays.asList(new ParameterDefinition(0, ParameterType.build("BYTES16"))));

    eventSpec.setNonIndexedParameterDefinitions(
            Arrays.asList(new ParameterDefinition(1, ParameterType.build("BYTES16"))));

    eventSpec.setEventName(eventEmitter.DUMMYEVENTBYTES16_EVENT.getName());

    registerEventFilter(createFilter(null , eventEmitter.getContractAddress(), eventSpec));

    //Generate random 16 byte value
    byte[] rndBytes = randomBytesValue(16);

    eventEmitter.emitEventBytes16(rndBytes).send();

    waitForContractEventMessages(1);

    final ContractEventDetails event = getBroadcastContractEvents().get(0);
    final String valueHex = Numeric.toHexString(rndBytes, 0, 16, true);

    assertEquals(valueHex, event.getNonIndexedParameters().get(0).getValueString());
    assertEquals(valueHex, event.getIndexedParameters().get(0).getValueString());
}
 
Example 19
Source File: Hash.java    From web3j with Apache License 2.0 2 votes vote down vote up
/**
 * Keccak-256 hash function.
 *
 * @param hexInput hex encoded input data with optional 0x prefix
 * @return hash value as hex encoded string
 */
public static String sha3(String hexInput) {
    byte[] bytes = Numeric.hexStringToByteArray(hexInput);
    byte[] result = sha3(bytes);
    return Numeric.toHexString(result);
}
 
Example 20
Source File: Hash.java    From etherscan-explorer with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Keccak-256 hash function.
 *
 * @param hexInput hex encoded input data with optional 0x prefix
 * @return hash value as hex encoded string
 */
public static String sha3(String hexInput) {
    byte[] bytes = Numeric.hexStringToByteArray(hexInput);
    byte[] result = sha3(bytes);
    return Numeric.toHexString(result);
}