本文整理汇总了Java中org.web3j.utils.Numeric类的典型用法代码示例。如果您正苦于以下问题:Java Numeric类的具体用法?Java Numeric怎么用?Java Numeric使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Numeric类属于org.web3j.utils包,在下文中一共展示了Numeric类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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();
}
示例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) + "\"";
}
示例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));
}
示例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));
}
示例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());
}
示例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();
}
}
示例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);
}
}
示例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);
}
示例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);
}
示例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());
}
示例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);
}
示例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)));
}
示例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)));
}
示例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)));
}