org.web3j.utils.Numeric Java Examples

The following examples show how to use org.web3j.utils.Numeric. 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: WasmFunctionEncoder.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public static String encodeConstructor(String code, List<?> inputParameters) {
	List<Object> parameters = new ArrayList<>();
	// parameters.add(DEPLOY_METHOD_NAME);
	parameters.add(fnvOne64Hash(DEPLOY_METHOD_NAME));
	for (Object o : inputParameters) {
		if (!o.equals(Void.class)) {
			parameters.add(o);
		}
	}
	byte[] parameterData = RLPCodec.encode(parameters);

	byte[] codeBinary = Numeric.hexStringToByteArray(code);
	Object[] objs = new Object[] { codeBinary, parameterData };
	byte[] data = RLPCodec.encode(objs);

	byte[] result = new byte[MAGIC_NUM.length + data.length];
	System.arraycopy(MAGIC_NUM, 0, result, 0, MAGIC_NUM.length);
	System.arraycopy(data, 0, result, MAGIC_NUM.length, data.length);

	return Numeric.toHexStringNoPrefix(result);
}
 
Example #2
Source File: RequestTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testEthSendTransaction() throws Exception {
    web3j.platonSendTransaction(new Transaction(
            "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
            BigInteger.ONE,
            Numeric.toBigInt("0x9184e72a000"),
            Numeric.toBigInt("0x76c0"),
            "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
            Numeric.toBigInt("0x9184e72a"),
            "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb"
                    + "970870f072445675058bb8eb970870f072445675")).send();

    //CHECKSTYLE:OFF
    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"platon_sendTransaction\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\",\"nonce\":\"0x1\"}],\"id\":1}");
    //CHECKSTYLE:ON
}
 
Example #3
Source File: SignTransactionIT.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSignTransaction() throws Exception {
    boolean accountUnlocked = unlockAccount();
    assertTrue(accountUnlocked);

    RawTransaction rawTransaction = createTransaction();

    byte[] encoded = TransactionEncoder.encode(rawTransaction);
    byte[] hashed = Hash.sha3(encoded);

    EthSign ethSign = web3j.ethSign(ALICE.getAddress(), Numeric.toHexString(hashed))
            .sendAsync().get();

    String signature = ethSign.getSignature();
    assertNotNull(signature);
    assertFalse(signature.isEmpty());
}
 
Example #4
Source File: Transaction.java    From web3j with Apache License 2.0 6 votes vote down vote up
public Transaction(
        String from,
        BigInteger nonce,
        BigInteger gasPrice,
        BigInteger gasLimit,
        String to,
        BigInteger value,
        String data,
        BigInteger gasPremium,
        BigInteger feeCap) {
    this.from = from;
    this.to = to;
    this.gas = gasLimit;
    this.gasPrice = gasPrice;
    this.value = value;

    if (data != null) {
        this.data = Numeric.prependHexPrefix(data);
    }

    this.nonce = nonce;
    this.gasPremium = gasPremium;
    this.feeCap = feeCap;
}
 
Example #5
Source File: PrivateTransactionEncoderTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignLegacyTransaction() {
    final String expected =
            "0xf8d4808203e8832dc6c094627306090abab3a6e1400e9345bc60c78a8bef578080820fe8a0e0b547d71d7a23d52382288b3a2a5a1610e0b504c404cc5009d7ada97d9015b2a076e997a83856d876fa2397b74510890eea3b73ffeda33daa4188120dac42d62fa0035695b4cc4b0941e60551d7a19cf30603db5bfc23e5ac43a56f57f25f75486af842a0035695b4cc4b0941e60551d7a19cf30603db5bfc23e5ac43a56f57f25f75486aa02a8d9b56a0fe9cd94d60be4413bcb721d3a7be27ed8e28b3a6346df874ee141b8a72657374726963746564";
    final RawPrivateTransaction privateTransactionCreation =
            new RawPrivateTransaction(
                    BigInteger.ZERO,
                    BigInteger.valueOf(1000),
                    BigInteger.valueOf(3000000),
                    "0x627306090abab3a6e1400e9345bc60c78a8bef57",
                    "0x",
                    MOCK_ENCLAVE_KEY,
                    MOCK_PRIVATE_FOR,
                    null,
                    RESTRICTED);
    final long chainId = 2018;
    final String privateKey =
            "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63";
    final Credentials credentials = Credentials.create(privateKey);
    final String privateRawTransaction =
            Numeric.toHexString(
                    PrivateTransactionEncoder.signMessage(
                            privateTransactionCreation, chainId, credentials));

    assertEquals(expected, privateRawTransaction);
}
 
Example #6
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 #7
Source File: RequestTest.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testEthSendTransaction() throws Exception {
    web3j.ethSendTransaction(new Transaction(
            "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
            BigInteger.ONE,
            Numeric.toBigInt("0x9184e72a000"),
            Numeric.toBigInt("0x76c0"),
            "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
            Numeric.toBigInt("0x9184e72a"),
            "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb"
                    + "970870f072445675058bb8eb970870f072445675")).send();

    //CHECKSTYLE:OFF
    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"to\":\"0xb60e8dd61c5d32be8058bb8eb970870f07233155\",\"gas\":\"0x76c0\",\"gasPrice\":\"0x9184e72a000\",\"value\":\"0x9184e72a\",\"data\":\"0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675\",\"nonce\":\"0x1\"}],\"id\":1}");
    //CHECKSTYLE:ON
}
 
Example #8
Source File: TransactionEncoderTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEip155Encode() {
    assertThat(TransactionEncoder.encode(createEip155RawTransaction(), (byte) 1),
            is(Numeric.hexStringToByteArray(
                    "0xec098504a817c800825208943535353535353535353535353535353535353535880de0"
                            + "b6b3a764000080018080")));
}
 
Example #9
Source File: PrivateTransactionDecoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecoding() {
    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_PRIVATE_FOR,
                    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_PRIVATE_FOR, result.getPrivateFor().get());
    assertEquals(RESTRICTED, result.getRestriction());
}
 
Example #10
Source File: RequestTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEthGetFilterLogs() throws Exception {
    web3j.platonGetFilterLogs(Numeric.toBigInt("0x16")).send();

    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"platon_getFilterLogs\","
            + "\"params\":[\"0x16\"],\"id\":1}");
}
 
Example #11
Source File: PlatOnTypeDecoderTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUintDecode() {

    assertThat(PlatOnTypeDecoder.decode(
    		Numeric.hexStringToByteArray("0000000000000000"),
            Uint64.class
            ),
            is(new Uint64(BigInteger.ZERO)));

    assertThat(PlatOnTypeDecoder.decode(
    		Numeric.hexStringToByteArray("7fffffffffffffff"),
            Uint64.class
            ),
            is(new Uint64(BigInteger.valueOf(Long.MAX_VALUE))));
}
 
Example #12
Source File: TransactionReceipt.java    From web3j with Apache License 2.0 5 votes vote down vote up
public boolean isStatusOK() {
    if (null == getStatus()) {
        return true;
    }
    BigInteger statusQuantity = Numeric.decodeQuantity(getStatus());
    return BigInteger.ONE.equals(statusQuantity);
}
 
Example #13
Source File: StructuredDataTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHashData() throws RuntimeException, IOException {
    StructuredDataEncoder dataEncoder = new StructuredDataEncoder(jsonMessageString);
    byte[] dataHash =
            dataEncoder.hashMessage(
                    dataEncoder.jsonMessageObject.getPrimaryType(),
                    (HashMap<String, Object>) dataEncoder.jsonMessageObject.getMessage());
    String expectedMessageStructHash =
            "0xc52c0ee5d84264471806290a3f2c4cecf" + "c5490626bf912d01f240d7a274b371e";

    assertEquals(Numeric.toHexString(dataHash), expectedMessageStructHash);
}
 
Example #14
Source File: ProposalContract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private Function createDeclareVersionFunction(ProgramVersion programVersion, String verifier)  {
    Function function = new Function(FunctionType.DECLARE_VERSION_FUNC_TYPE,
            Arrays.asList(new BytesType(Numeric.hexStringToByteArray(verifier)),
                    new Uint32(programVersion.getProgramVersion()),
                    new BytesType(Numeric.hexStringToByteArray(programVersion.getProgramVersionSign()))));
    return function;
}
 
Example #15
Source File: Transfer.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private TransactionReceipt send(String toAddress, BigDecimal value, Convert.Unit unit, BigInteger gasPrice,
                                BigInteger gasLimit) throws IOException, InterruptedException,
        TransactionException {

    BigDecimal weiValue = Convert.toVon(value, unit);
    if (!Numeric.isIntegerValue(weiValue)) {
        throw new UnsupportedOperationException(
                "Non decimal Wei value provided: " + value + " " + unit.toString()
                        + " = " + weiValue + " Wei");
    }

    return send(toAddress, "", weiValue.toBigIntegerExact(), gasPrice, gasLimit);
}
 
Example #16
Source File: FunctionReturnDecoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedDynamicBytesValue() {
    DynamicBytes bytes = new DynamicBytes(new byte[] {1, 2, 3, 4, 5});
    String encoded = TypeEncoder.encodeDynamicBytes(bytes);
    String hash = Hash.sha3(encoded);

    assertEquals(
            FunctionReturnDecoder.decodeIndexedValue(
                    hash, new TypeReference<DynamicBytes>() {}),
            (new Bytes32(Numeric.hexStringToByteArray(hash))));
}
 
Example #17
Source File: DelegateContract.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private Function createUnDelegateFunction(String nodeId, BigInteger stakingBlockNum, BigInteger amount) {
	Function function = new Function(FunctionType.WITHDREW_DELEGATE_FUNC_TYPE,
            Arrays.asList(new Uint64(stakingBlockNum)
                    , new BytesType(Numeric.hexStringToByteArray(nodeId))
                    , new Uint256(amount)));
    return function;
}
 
Example #18
Source File: RequestTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testEthUninstallFilter() throws Exception {
    web3j.platonUninstallFilter(Numeric.toBigInt("0xb")).send();

    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"platon_uninstallFilter\","
            + "\"params\":[\"0x0b\"],\"id\":1}");
}
 
Example #19
Source File: FunctionReturnDecoderTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeIndexedBytes32Value() {
    String rawInput = "0x1234567890123456789012345678901234567890123456789012345678901234";
    byte[] rawInputBytes = Numeric.hexStringToByteArray(rawInput);

    assertThat(FunctionReturnDecoder.decodeIndexedValue(
            rawInput,
            new TypeReference<Bytes32>(){}),
            equalTo(new Bytes32(rawInputBytes)));
}
 
Example #20
Source File: PrivateTransactionDecoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodingSignedChainId() throws Exception {
    final BigInteger nonce = BigInteger.ZERO;
    final BigInteger gasPrice = BigInteger.ONE;
    final BigInteger gasLimit = BigInteger.TEN;
    final String to = "0x0add5355";
    final long chainId = 2018L;
    final RawPrivateTransaction rawTransaction =
            RawPrivateTransaction.createTransaction(
                    nonce,
                    gasPrice,
                    gasLimit,
                    to,
                    "",
                    MOCK_ENCLAVE_KEY,
                    MOCK_PRIVATE_FOR,
                    RESTRICTED);
    final String privateKey =
            "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63";
    final Credentials credentials = Credentials.create(privateKey);
    byte[] signedMessage =
            PrivateTransactionEncoder.signMessage(rawTransaction, chainId, credentials);
    final String hexMessage = Numeric.toHexString(signedMessage);

    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_PRIVATE_FOR, result.getPrivateFor().get());
    assertEquals(RESTRICTED, result.getRestriction());
    assertTrue(result instanceof SignedRawPrivateTransaction);
    final SignedRawPrivateTransaction signedResult = (SignedRawPrivateTransaction) result;
    assertEquals(credentials.getAddress(), signedResult.getFrom());
    signedResult.verify(credentials.getAddress());
    assertEquals(chainId, signedResult.getChainId().longValue());
}
 
Example #21
Source File: StructuredDataTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashStructuredMessage() throws RuntimeException, IOException {
    StructuredDataEncoder dataEncoder = new StructuredDataEncoder(jsonMessageString);
    byte[] hashStructuredMessage = dataEncoder.hashStructuredData();
    String expectedDomainStructHash =
            "0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20" + "f02e86244efddf30957bd2";

    assertEquals(Numeric.toHexString(hashStructuredMessage), expectedDomainStructHash);
}
 
Example #22
Source File: JsonRpc2_0Web3j.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Request<?, EthUninstallFilter> ethUninstallFilter(BigInteger filterId) {
    return new Request<>(
            "eth_uninstallFilter",
            Arrays.asList(Numeric.toHexStringWithPrefixSafe(filterId)),
            web3jService,
            EthUninstallFilter.class);
}
 
Example #23
Source File: TransactionEncoderTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEip155Transaction() {
    // https://github.com/ethereum/EIPs/issues/155
    Credentials credentials =
            Credentials.create(
                    "0x4646464646464646464646464646464646464646464646464646464646464646");

    assertArrayEquals(
            TransactionEncoder.signMessage(createEip155RawTransaction(), (byte) 1, credentials),
            (Numeric.hexStringToByteArray(
                    "0xf86c098504a817c800825208943535353535353535353535353535353535353535880"
                            + "de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d"
                            + "3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf55"
                            + "5c9f3dc64214b297fb1966a3b6d83")));
}
 
Example #24
Source File: SellDetailActivity.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private BigInteger getPriceInWei() {
    //now convert to microWei
    long microEth = (int)(sellPriceValue * 1000000.0);
    byte[] max = Numeric.hexStringToByteArray("FFFFFFFF");
    BigInteger maxValue = new BigInteger(1, max);
    if (microEth > maxValue.longValue()) microEth = 0; //check on UI screen if amount is more than we can handle
    //now convert to Wei
    return Convert.toWei(Long.toString(microEth), Convert.Unit.SZABO).toBigInteger();
}
 
Example #25
Source File: JsonRpc2_0Web3j.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, PlatonTransaction> platonGetTransactionByBlockNumberAndIndex(
        DefaultBlockParameter defaultBlockParameter, BigInteger transactionIndex) {
    return new Request<>(
            "platon_getTransactionByBlockNumberAndIndex",
            Arrays.asList(
                    defaultBlockParameter.getValue(),
                    Numeric.encodeQuantity(transactionIndex)),
            web3jService,
            PlatonTransaction.class);
}
 
Example #26
Source File: JsonRpc2_0Web3j.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, EthLog> ethGetFilterLogs(BigInteger filterId) {
    return new Request<>(
            "eth_getFilterLogs",
            Arrays.asList(Numeric.toHexStringWithPrefixSafe(filterId)),
            web3jService,
            EthLog.class);
}
 
Example #27
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEthGetTransactionByBlockNumberAndIndex() throws Exception {
    web3j.ethGetTransactionByBlockNumberAndIndex(
                    DefaultBlockParameter.valueOf(Numeric.toBigInt("0x29c")), BigInteger.ZERO)
            .send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByBlockNumberAndIndex\","
                    + "\"params\":[\"0x29c\",\"0x0\"],\"id\":1}");
}
 
Example #28
Source File: JsonRpc2_0Web3j.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Request<?, ShhMessages> shhGetFilterChanges(BigInteger filterId) {
    return new Request<>(
            "shh_getFilterChanges",
            Arrays.asList(Numeric.toHexStringWithPrefixSafe(filterId)),
            web3jService,
            ShhMessages.class);
}
 
Example #29
Source File: RequestTest.java    From web3j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEthGetFilterChanges() throws Exception {
    web3j.ethGetFilterChanges(Numeric.toBigInt("0x16")).send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getFilterChanges\","
                    + "\"params\":[\"0x16\"],\"id\":1}");
}
 
Example #30
Source File: Bip32Test.java    From web3j with Apache License 2.0 5 votes vote down vote up
private void testGenerated(String seed, String expectedPriv, String expectedPub, int[] path) {
    Bip32ECKeyPair pair = Bip32ECKeyPair.generateKeyPair(Numeric.hexStringToByteArray(seed));
    assertNotNull(pair);

    pair = Bip32ECKeyPair.deriveKeyPair(pair, path);
    assertNotNull(pair);

    assertEquals(expectedPriv, Base58.encode(addChecksum(serializePrivate(pair))));
    assertEquals(expectedPub, Base58.encode(addChecksum(serializePublic(pair))));
}