• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java Numeric类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.web3j.utils.Numeric的典型用法代码示例。如果您正苦于以下问题:Java Numeric类的具体用法?Java Numeric怎么用?Java Numeric使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Numeric类属于org.web3j.utils包,在下文中一共展示了Numeric类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: testCreateAccountFromScratch

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void testCreateAccountFromScratch() throws Exception {
	
	// create new private/public key pair
	ECKeyPair keyPair = Keys.createEcKeyPair();
	
	BigInteger publicKey = keyPair.getPublicKey();
	String publicKeyHex = Numeric.toHexStringWithPrefix(publicKey);
	
	BigInteger privateKey = keyPair.getPrivateKey();
	String privateKeyHex = Numeric.toHexStringWithPrefix(privateKey);
	
	// create credentials + address from private/public key pair
	Credentials credentials = Credentials.create(new ECKeyPair(privateKey, publicKey));
	String address = credentials.getAddress();
	
	// print resulting data of new account
	System.out.println("private key: '" + privateKeyHex + "'");
	System.out.println("public key: '" + publicKeyHex + "'");
	System.out.println("address: '" + address + "'\n");
	
	// test (1) check if it's possible to transfer funds to new address
	BigInteger amountWei = Convert.toWei("0.131313", Convert.Unit.ETHER).toBigInteger();
	transferWei(getCoinbase(), address, amountWei);

	BigInteger balanceWei = getBalanceWei(address);
	BigInteger nonce = getNonce(address);
	
	assertEquals("Unexpected nonce for 'to' address", BigInteger.ZERO, nonce);
	assertEquals("Unexpected balance for 'to' address", amountWei, balanceWei);

	// test (2) funds can be transferred out of the newly created account
	BigInteger txFees = Web3jConstants.GAS_LIMIT_ETHER_TX.multiply(Web3jConstants.GAS_PRICE);
	RawTransaction txRaw = RawTransaction
			.createEtherTransaction(
					nonce, 
					Web3jConstants.GAS_PRICE, 
					Web3jConstants.GAS_LIMIT_ETHER_TX, 
					getCoinbase(), 
					amountWei.subtract(txFees));

	// sign raw transaction using the sender's credentials
	byte[] txSignedBytes = TransactionEncoder.signMessage(txRaw, credentials);
	String txSigned = Numeric.toHexString(txSignedBytes);

	// send the signed transaction to the ethereum client
	EthSendTransaction ethSendTx = web3j
			.ethSendRawTransaction(txSigned)
			.sendAsync()
			.get();

	Error error = ethSendTx.getError();
	String txHash = ethSendTx.getTransactionHash();
	assertNull(error);		
	assertFalse(txHash.isEmpty());
	
	waitForReceipt(txHash);

	assertEquals("Unexpected nonce for 'to' address", BigInteger.ONE, getNonce(address));
	assertTrue("Balance for 'from' address too large: " + getBalanceWei(address), getBalanceWei(address).compareTo(txFees) < 0);
}
 
开发者ID:matthiaszimmermann,项目名称:web3j_demo,代码行数:62,代码来源:CreateAccountTest.java


示例2: toBytes

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Override
    public byte[] toBytes() {
/*
    uint256 sspPayment;
    uint256 auditorPayment;
    uint64 totalImpressions;
    uint64 fraudImpressions;
    assembly {
      sspPayment := mload(result)
      auditorPayment := mload(add(result, 0x20))
      totalImpressions := mload(add(result, 0x40))
      fraudImpressions := mload(add(result, 0x48))
    }

*/
        ByteBuffer buffer = ByteBuffer.allocate(Uint256.MAX_BYTE_LENGTH + Uint256.MAX_BYTE_LENGTH + Uint64.MAX_BYTE_LENGTH + Uint64.MAX_BYTE_LENGTH);
        buffer.put(Numeric.toBytesPadded(sspPayment(), Uint256.MAX_BYTE_LENGTH));
        buffer.put(Numeric.toBytesPadded(auditorPayment(), Uint256.MAX_BYTE_LENGTH));
        buffer.put(Numeric.toBytesPadded(BigInteger.valueOf(totalImpressions), Uint64.MAX_BYTE_LENGTH));
        buffer.put(Numeric.toBytesPadded(BigInteger.valueOf(fraudImpressions), Uint64.MAX_BYTE_LENGTH));
        return buffer.array();
    }
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:23,代码来源:RtbResult.java


示例3: json

import org.web3j.utils.Numeric; //导入依赖的package包/类
private static String json(Type<?> p) {
    if (p == null) return "null";
    if (p instanceof NumericType || p instanceof Bool) {
        return p.getValue().toString();
    } 
    if (p instanceof Array) {
        return "[" + json(((Array<?>) p).getValue()) + "]";
    }
    Object value = p.getValue();
    String str;
    if (value instanceof byte[]) {
        str = Numeric.toHexStringNoPrefix((byte[]) value);
    } else {
        str = value.toString();
    }
    return "\"" + StringEscapeUtils.escapeJava(str) + "\"";
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:18,代码来源:CallUtil.java


示例4: test

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void test() throws IOException, ExecutionException, InterruptedException {
    Address senderAddress = new Address(cfg.getMainCredentials().getAddress());
    Address contractAddress = new Address("0x1");
    long nonce = 123L;
    BigInteger completedTransfers = BigInteger.TEN;
    
    ChannelTransaction state = new ChannelTransaction();
    state.setSender(senderAddress);
    state.setChannelId(1);
    state.setBlockNumber(1L);
    state.setData("DATA".getBytes());
    
    byte[] hash = callHash("hashState", senderAddress, new Uint256(nonce), new Uint256(completedTransfers));
    Assert.assertEquals(Numeric.toHexString(state.hash()), Numeric.toHexString(hash));
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:17,代码来源:HashTest.java


示例5: createTokenTransferData

import org.web3j.utils.Numeric; //导入依赖的package包/类
public static byte[] createTokenTransferData(String to, BigInteger tokenAmount) {
    List<Type> params = Arrays.asList(new Address(to), new Uint256(tokenAmount));

    List<TypeReference<?>> returnTypes = Arrays.<TypeReference<?>>asList(new TypeReference<Bool>() {
    });

    Function function = new Function("transfer", params, returnTypes);
    String encodedFunction = FunctionEncoder.encode(function);
    return Numeric.hexStringToByteArray(Numeric.cleanHexPrefix(encodedFunction));
}
 
开发者ID:TrustWallet,项目名称:trust-wallet-android,代码行数:11,代码来源:TokenRepository.java


示例6: createTransaction

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Override
public Single<String> createTransaction(Wallet from, String toAddress, BigInteger subunitAmount, BigInteger gasPrice, BigInteger gasLimit, byte[] data, String password) {
	final Web3j web3j = Web3jFactory.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

	return Single.fromCallable(() -> {
		EthGetTransactionCount ethGetTransactionCount = web3j
				.ethGetTransactionCount(from.address, DefaultBlockParameterName.LATEST)
				.send();
		return ethGetTransactionCount.getTransactionCount();
	})
	.flatMap(nonce -> accountKeystoreService.signTransaction(from, password, toAddress, subunitAmount, gasPrice, gasLimit, nonce.longValue(), data, networkRepository.getDefaultNetwork().chainId))
	.flatMap(signedMessage -> Single.fromCallable( () -> {
		EthSendTransaction raw = web3j
				.ethSendRawTransaction(Numeric.toHexString(signedMessage))
				.send();
		if (raw.hasError()) {
			throw new ServiceException(raw.getError().getMessage());
		}
		return raw.getTransactionHash();
	})).subscribeOn(Schedulers.io());
}
 
开发者ID:TrustWallet,项目名称:trust-wallet-android,代码行数:22,代码来源:TransactionRepository.java


示例7: generateWallet

import org.web3j.utils.Numeric; //导入依赖的package包/类
public static Wallet generateWallet(Context context, ECKeyPair ecKeyPair,
                                    final String password)
        throws WalletNotGeneratedException
{
    try {
        final String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair));
        final File destDirectory = Environment.getExternalStorageDirectory().getAbsoluteFile();
        Log.d(TAG, Environment.getExternalStorageState());
        final String fileName = WalletUtils.generateWalletFile(password, ecKeyPair, destDirectory, false);
        final String destFilePath = destDirectory + "/" + fileName;

        return new Wallet(ecKeyPair, destFilePath, address);
    } catch (CipherException | IOException e)
    {
        e.printStackTrace();
        throw new WalletNotGeneratedException();
    }
}
 
开发者ID:humaniq,项目名称:humaniq-android,代码行数:19,代码来源:Wallet.java


示例8: decodeBytes

import org.web3j.utils.Numeric; //导入依赖的package包/类
static <T extends Bytes> T decodeBytes(String input, int offset, Class<T> type) {
    try {
        String simpleName = type.getSimpleName();
        String[] splitName = simpleName.split(Bytes.class.getSimpleName());
        int length = Integer.parseInt(splitName[1]);
        int hexStringLength = length << 1;

        byte[] bytes = Numeric.hexStringToByteArray(
                input.substring(offset, offset + hexStringLength));
        return type.getConstructor(byte[].class).newInstance(bytes);
    } catch (NoSuchMethodException | SecurityException
            | InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException e) {
        throw new UnsupportedOperationException(
                "Unable to create instance of " + type.getName(), e);
    }
}
 
开发者ID:web3j,项目名称:web3j,代码行数:18,代码来源:TypeDecoder.java


示例9: encodeNumeric

import org.web3j.utils.Numeric; //导入依赖的package包/类
static String encodeNumeric(NumericType numericType) {
    byte[] rawValue = toByteArray(numericType);
    byte paddingValue = getPaddingValue(numericType);
    byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH];
    if (paddingValue != 0) {
        for (int i = 0; i < paddedRawValue.length; i++) {
            paddedRawValue[i] = paddingValue;
        }
    }

    System.arraycopy(
            rawValue, 0,
            paddedRawValue, MAX_BYTE_LENGTH - rawValue.length,
            rawValue.length);
    return Numeric.toHexStringNoPrefix(paddedRawValue);
}
 
开发者ID:web3j,项目名称:web3j,代码行数:17,代码来源:TypeEncoder.java


示例10: onReceipt

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Override
protected void onReceipt(BlockState state, BlockContext context, TransactionReceipt receipt) throws Exception {
    //refresh blockchain state
    state.blockchain.executeAsync(state, context);
    byte[] postedHash = getBlockchainHash(state);
    if (postedHash == null) {
        throw new IllegalStateException("Result hash not applied");
    }
    if (!Arrays.equals(resultHash, postedHash)) {
        throw new IllegalStateException("Result hashes not equal: " + Numeric.toHexStringNoPrefix(resultHash) + " and " + Numeric.toHexStringNoPrefix(postedHash));
    }
    super.onReceipt(state, context, receipt);
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:14,代码来源:EthSetBlockResultTask.java


示例11: getContractCode

import org.web3j.utils.Numeric; //导入依赖的package包/类
public static String getContractCode(Web3j web3j, String contractAddress) throws IOException {
    EthGetCode ethGetCode = web3j
        .ethGetCode(contractAddress, DefaultBlockParameterName.LATEST)
        .send();

    if (ethGetCode.hasError()) {
        throw new IllegalStateException("Failed to get code for " + contractAddress + ": " + ethGetCode.getError().getMessage());
    }

    return Numeric.cleanHexPrefix(ethGetCode.getCode());
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:12,代码来源:CryptoUtil.java


示例12: decodeKeyPair

import org.web3j.utils.Numeric; //导入依赖的package包/类
public static KeyPair decodeKeyPair(ECKeyPair ecKeyPair) {
    byte[] bytes = Numeric.toBytesPadded(ecKeyPair.getPublicKey(), 64);
    BigInteger x = Numeric.toBigInt(Arrays.copyOfRange(bytes, 0, 32));
    BigInteger y = Numeric.toBigInt(Arrays.copyOfRange(bytes, 32, 64));
    ECPoint q = curve.createPoint(x, y);
    BCECPublicKey publicKey = new BCECPublicKey(ALGORITHM, new ECPublicKeyParameters(q, dp), BouncyCastleProvider.CONFIGURATION);
    BCECPrivateKey privateKey = new BCECPrivateKey(ALGORITHM, new ECPrivateKeyParameters(ecKeyPair.getPrivateKey(), dp), publicKey, p, BouncyCastleProvider.CONFIGURATION);
    return new KeyPair(publicKey, privateKey);
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:10,代码来源:CryptoUtil.java


示例13: testa2

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void testa2() throws IOException, ExecutionException, InterruptedException {
    Address a1 = new Address("b508d41ecb22e9b9bb85c15b5fb3a90cdaddc4ea");
    Address a2 = new Address("bb9208c172166497cd04958dce1a3f67b28e4d7b");
    byte[] hash = callHash("hasha2", a1, a2);
    Assert.assertEquals(Numeric.toHexString(hash), Numeric.toHexString(CryptoUtil.soliditySha3(a1, a2)));
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:8,代码来源:HashTest.java


示例14: test2

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void test2() throws IOException, ExecutionException, InterruptedException {
    Uint256 int1 = new Uint256(new BigInteger("1"));
    Uint256 int2 = new Uint256(new BigInteger("2"));
    byte[] hash = callHash("hash2", int1, int2);
    Assert.assertEquals(Numeric.toHexString(hash), Numeric.toHexString(CryptoUtil.soliditySha3(int1, int2)));
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:8,代码来源:HashTest.java


示例15: test3

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void test3() throws IOException, ExecutionException, InterruptedException {
    Uint256 int1 = new Uint256(new BigInteger("1"));
    Uint256 int2 = new Uint256(new BigInteger("2"));
    Uint256 int3 = new Uint256(new BigInteger("3"));
    byte[] hash = callHash("hash3", int1, int2, int3);
    Assert.assertEquals(Numeric.toHexString(hash), Numeric.toHexString(CryptoUtil.soliditySha3(int1, int2, int3)));
    Assert.assertEquals(Numeric.toHexString(hash), Numeric.toHexString(CryptoUtil.soliditySha3(int1, int2, int3)));
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:10,代码来源:HashTest.java


示例16: soliditySha3

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void soliditySha3() throws Exception {
    Assert.assertEquals(
        "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6",
        Numeric.toHexString(CryptoUtil.soliditySha3(1))
    );
    Assert.assertEquals(
        "0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6",
        Numeric.toHexString(CryptoUtil.soliditySha3(1))
    );
    Assert.assertEquals(
        "0xa9c584056064687e149968cbab758a3376d22aedc6a55823d1b3ecbee81b8fb9",
        Numeric.toHexString(CryptoUtil.soliditySha3(-1))
    );
    Assert.assertEquals(
        "0x26700e13983fefbd9cf16da2ed70fa5c6798ac55062a4803121a869731e308d2",
        Numeric.toHexString(CryptoUtil.soliditySha3(BigInteger.valueOf(100)))
    );
    Assert.assertEquals(
        "0x26700e13983fefbd9cf16da2ed70fa5c6798ac55062a4803121a869731e308d2",
        Numeric.toHexString(CryptoUtil.soliditySha3(BigInteger.valueOf(100)))
    );
    Address address = new Address("abcdef");
    Assert.assertEquals(
        Numeric.toHexStringNoPrefixZeroPadded(address.toUint160().getValue(), 40),
        Numeric.toHexStringNoPrefix(Numeric.toBytesPadded(address.toUint160().getValue(), 20))
    );
    Assert.assertEquals(
        Hash.sha3(Numeric.toHexStringNoPrefixZeroPadded(address.toUint160().getValue(), 40)),
        Numeric.toHexString(CryptoUtil.soliditySha3(address))
    );
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:33,代码来源:TestCryptoUtil.java


示例17: quorumCanonicalHash

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Override
public Request<?, CanonicalHash> quorumCanonicalHash(BigInteger blockHeight) {
    return new Request<>(
            "quorum_canonicalHash",
            Collections.singletonList(Numeric.encodeQuantity(blockHeight)),
            web3jService,
            CanonicalHash.class);
}
 
开发者ID:web3j,项目名称:quorum,代码行数:9,代码来源:JsonRpc2_0Quorum.java


示例18: createSignedTransaction

import org.web3j.utils.Numeric; //导入依赖的package包/类
public Transaction createSignedTransaction(String to, BigInteger amountWei, String data, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit) {
  Transaction tx = new Transaction(to, amountWei, data, nonce, gasPrice, gasLimit);

  tx.setFromAddress(getAddress());
  byte[] signedMessage = TransactionEncoder.signMessage(tx.getRawTransaction(), getCredentials());
  tx.setSignedContent(Numeric.toHexString(signedMessage));

  return tx;
}
 
开发者ID:BSI-Business-Systems-Integration-AG,项目名称:trading-network,代码行数:10,代码来源:Account.java


示例19: testEthGetLogsWithNumericBlockRange

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void testEthGetLogsWithNumericBlockRange() throws Exception {
    web3j.ethGetLogs(new EthFilter(
            DefaultBlockParameter.valueOf(Numeric.toBigInt("0xe8")),
            DefaultBlockParameter.valueOf("latest"), ""))
            .send();

    verifyResult(
            "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\","
                    + "\"params\":[{\"topics\":[],\"fromBlock\":\"0xe8\","
                    + "\"toBlock\":\"latest\",\"address\":[\"\"]}],\"id\":1}");
}
 
开发者ID:web3j,项目名称:web3j,代码行数:13,代码来源:RequestTest.java


示例20: testEthGetUncleCountByBlockNumber

import org.web3j.utils.Numeric; //导入依赖的package包/类
@Test
public void testEthGetUncleCountByBlockNumber() throws Exception {
    web3j.ethGetUncleCountByBlockNumber(
            DefaultBlockParameter.valueOf(Numeric.toBigInt("0xe8"))).send();

    verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_getUncleCountByBlockNumber\","
            + "\"params\":[\"0xe8\"],\"id\":1}");
}
 
开发者ID:web3j,项目名称:web3j,代码行数:9,代码来源:RequestTest.java



注:本文中的org.web3j.utils.Numeric类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java MethodNotSupportedException类代码示例发布时间:2022-05-22
下一篇:
Java LayoutUtil类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap