Java Code Examples for org.web3j.crypto.Credentials#create()

The following examples show how to use org.web3j.crypto.Credentials#create() . 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: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void loadFromJson(Uri uri, String pwd) {
    sharedManager.setJsonExcep("");
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        InputStream is = context.getContentResolver().openInputStream(uri);
        WalletFile walletFile = objectMapper.readValue(is, WalletFile.class);
        credentials = Credentials.create(Wallet.decrypt(pwd, walletFile));
    } catch (JsonParseException jpe) {
        sharedManager.setJsonExcep("JsonParseException");
        jpe.printStackTrace();
    } catch (CipherException ce) {
        if (ce.getMessage().equals("Invalid password provided")){
            sharedManager.setJsonExcep("WrongPassword");
        } else {
            sharedManager.setJsonExcep("CipherException");
        }
        ce.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void loadFromJson(Uri uri, String pwd) {
    sharedManager.setJsonExcep("");
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        InputStream is = context.getContentResolver().openInputStream(uri);
        WalletFile walletFile = objectMapper.readValue(is, WalletFile.class);
        credentials = Credentials.create(Wallet.decrypt(pwd, walletFile));
    } catch (JsonParseException jpe) {
        sharedManager.setJsonExcep("JsonParseException");
        jpe.printStackTrace();
    } catch (CipherException ce) {
        if (ce.getMessage().equals("Invalid password provided")) {
            sharedManager.setJsonExcep("WrongPassword");
        } else {
            sharedManager.setJsonExcep("CipherException");
        }
        ce.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: PrivateTransactionEncoderTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignBesuTransaction() {
    final String expected =
            "0xf8b1808203e8832dc6c094627306090abab3a6e1400e9345bc60c78a8bef578080820fe7a060c70c3f989ef5459021142959f8fc1ad6e5fe8542cf238484c6d6b8c8a6dbcca075727642ce691c4bf5ae945523cdd172d44b451ddfe11ae67c376f1e5c7069eea0035695b4cc4b0941e60551d7a19cf30603db5bfc23e5ac43a56f57f25f75486aa00f200e885ff29e973e2576b6600181d1b0a2b5294e30d9be4a1981ffb33a0b8c8a72657374726963746564";
    final RawPrivateTransaction privateTransactionCreation =
            new RawPrivateTransaction(
                    BigInteger.ZERO,
                    BigInteger.valueOf(1000),
                    BigInteger.valueOf(3000000),
                    "0x627306090abab3a6e1400e9345bc60c78a8bef57",
                    "0x",
                    MOCK_ENCLAVE_KEY,
                    null,
                    MOCK_PRIVACY_GROUP_ID,
                    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 4
Source File: KeyImporter.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private void createWalletFile(String privateKey) {
    if (!WalletUtils.isValidPrivateKey(privateKey)) {
        exitError("Invalid private key specified, must be "
                + PRIVATE_KEY_LENGTH_IN_HEX
                + " digit hex value");
    }

    Credentials credentials = Credentials.create(privateKey);
    String password = getPassword("Please enter a wallet file password: ");

    String destinationDir = getDestinationDir();
    File destination = createDir(destinationDir);

    try {
        String walletFileName = WalletUtils.generateWalletFile(
                password, credentials.getEcKeyPair(), destination, true);
        console.printf("Wallet file " + walletFileName
                + " successfully created in: " + destinationDir + "\n");
    } catch (CipherException | IOException e) {
        exitError(e);
    }
}
 
Example 5
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock(String privateKey, WalletCreationCallback callback){
    try {
        credentials = Credentials.create(privateKey);
        WalletCreationTask task = new WalletCreationTask(callback, credentials.getEcKeyPair());
        task.execute(BLOCK);
    } catch (NumberFormatException nfe) {
        Log.e("psd", "restoreFromBlock: " + nfe.toString());
        DebugHelper.logIventFirebase("restoreFromBlock", nfe.toString(), context);
    }
}
 
Example 6
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock(String privateKey, WalletCreationCallback callback) {
    try {
        credentials = Credentials.create(privateKey);
        WalletCreationTask task = new WalletCreationTask(callback, credentials.getEcKeyPair());
        task.execute(BLOCK);
    } catch (NumberFormatException e) {
        if (callback != null) {
            callback.onWalletCreated(null);
        }
        e.printStackTrace();
    }
}
 
Example 7
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock2(String privateKey, final Runnable callback) {
    credentials = Credentials.create(privateKey);
    WalletCreationTask2 task = new WalletCreationTask2(new WalletCreationCallback() {
        @Override
        public void onWalletCreated(WalletFile walletFile) {
            callback.run();
        }
    }, credentials.getEcKeyPair());
    task.execute(BLOCK);
}
 
Example 8
Source File: StakingContractTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws Exception {
	superCredentials = Credentials.create("0xa689f0879f53710e9e0c1025af410a530d6381eebb5916773195326e123b822b");
	System.out.println("superCredentials balance="+ web3j.platonGetBalance(superCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance());

	stakingCredentials = Credentials.create("0x690a32ceb7eab4131f7be318c1672d3b9b2dadeacba20b99432a7847c1e926e0");
	System.out.println("stakingCredentials balance="+ web3j.platonGetBalance(stakingCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance());
	
	benefitCredentials = Credentials.create("0x3581985348bffd03b286b37712165f7addf3a8d907b25efc44addf54117e9b91");
	System.out.println("benefitCredentials balance="+ web3j.platonGetBalance(benefitCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance());
  	
    stakingContract = StakingContract.load( web3j,stakingCredentials, chainId);    
}
 
Example 9
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock2(String privateKey, final Runnable callback){
    credentials = Credentials.create(privateKey);
    WalletCreationTask2 task = new WalletCreationTask2(new WalletCreationCallback() {
        @Override
        public void onWalletCreated(WalletFile walletFile) {
            callback.run();
        }
    }, credentials.getEcKeyPair());
    task.execute(BLOCK);
}
 
Example 10
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock0(String privateKey, final Runnable callback){
    credentials = Credentials.create(privateKey);
    WalletCreationTask task = new WalletCreationTask(new WalletCreationCallback() {
        @Override
        public void onWalletCreated(WalletFile walletFile) {
            callback.run();
        }
    }, credentials.getEcKeyPair());
    task.execute(BLOCK);
}
 
Example 11
Source File: TransferTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void transfer() throws Exception {
    Web3j web3j = Web3j.build(new HttpService("http://10.10.8.200:6789"));
    Credentials credentials = Credentials.create("0xa7f1d33a30c1e8b332443825f2209755c52086d0a88b084301a6727d9f84bf32");
    Transfer.sendFunds(web3j,credentials,"100","0x8b77ac9fabb6fe247ee91ca07ea4f62c6761e79b", BigDecimal.valueOf(100), Convert.Unit.LAT).send();
}
 
Example 12
Source File: DeployPrivateSmartContractTransaction.java    From besu with Apache License 2.0 5 votes vote down vote up
public DeployPrivateSmartContractTransaction(
    final Class<T> clazz,
    final String transactionSigningKey,
    final long chainId,
    final String privateFrom,
    final List<String> privateFor) {
  this.clazz = clazz;
  this.senderCredentials = Credentials.create(transactionSigningKey);
  this.chainId = chainId;
  this.privateFrom = Base64String.wrap(privateFrom);
  this.privateFor = Base64String.wrapList(privateFor);
}
 
Example 13
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void restoreFromBlock0(String privateKey, final Runnable callback) {
    credentials = Credentials.create(privateKey);
    WalletCreationTask task = new WalletCreationTask(new WalletCreationCallback() {
        @Override
        public void onWalletCreated(WalletFile walletFile) {
            callback.run();
        }
    }, credentials.getEcKeyPair());
    task.execute(BLOCK);
}
 
Example 14
Source File: LoadPrivateSmartContractTransaction.java    From besu with Apache License 2.0 5 votes vote down vote up
public LoadPrivateSmartContractTransaction(
    final String contractAddress,
    final Class<T> clazz,
    final String transactionSigningKey,
    final long chainId,
    final String privateFrom,
    final List<String> privateFor) {

  this.contractAddress = contractAddress;
  this.clazz = clazz;
  this.senderCredentials = Credentials.create(transactionSigningKey);
  this.chainId = chainId;
  this.privateFrom = Base64String.wrap(privateFrom);
  this.privateFor = Base64String.wrapList(privateFor);
}
 
Example 15
Source File: DeployPrivateSmartContractWithPrivacyGroupIdTransaction.java    From besu with Apache License 2.0 5 votes vote down vote up
public DeployPrivateSmartContractWithPrivacyGroupIdTransaction(
    final Class<T> clazz,
    final String transactionSigningKey,
    final long chainId,
    final String privateFrom,
    final String privacyGroupId) {
  this.clazz = clazz;
  this.senderCredentials = Credentials.create(transactionSigningKey);
  this.chainId = chainId;
  this.privateFrom = Base64String.wrap(privateFrom);
  this.privacyGroupId = Base64String.wrap(privacyGroupId);
}
 
Example 16
Source File: RegisterParams.java    From teku with Apache License 2.0 5 votes vote down vote up
Credentials getEth1Credentials() {
  if (eth1PrivateKeyOptions.eth1PrivateKey != null) {
    return Credentials.create(eth1PrivateKeyOptions.eth1PrivateKey);
  } else if (eth1PrivateKeyOptions.keystoreOptions != null) {
    return eth1CredentialsFromKeystore();
  } else {
    // not meant to happen
    throw new IllegalStateException("Private Key Options are not initialized");
  }
}
 
Example 17
Source File: IllegalSignatureCreationTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@Test
void ensureSignaturesCreatedHavePositiveValues() {
  // This problem was identified in Github Issue #247, which identified a specific
  // transaction being signed with a given key, resulted in the transaction being rejected by
  // Besu due to "INVALID SIGNATURE" - ultimately, it was came down to byte[] --> BigInt resulting
  // in negative value.
  final long chainId = 44844;

  final EthSendTransactionJsonParameters txnParams =
      new EthSendTransactionJsonParameters("0xf17f52151ebef6c7334fad080c5704d77216b732");
  txnParams.gasPrice("0x0");
  txnParams.gas("0x7600");
  txnParams.nonce("0x46");
  txnParams.value("0x1");
  txnParams.data("0x0");
  txnParams.receiver("0x627306090abaB3A6e1400e9345bC60c78a8BEf57");

  final EthTransaction txn = new EthTransaction(txnParams, null, null);
  final byte[] serialisedBytes = txn.rlpEncode(chainId);

  final CredentialTransactionSigner signer =
      new CredentialTransactionSigner(
          Credentials.create("ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f"));

  final Signature signature = signer.sign(serialisedBytes);

  assertThat(signature.getR().signum()).isOne();
  assertThat(signature.getS().signum()).isOne();
}
 
Example 18
Source File: CreateAccountTest.java    From web3j_demo with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 19
Source File: PrivateTransactionDecoderTest.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecodingSignedPrivacyGroup() throws Exception {
    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);
    final String privateKey =
            "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63";
    final Credentials credentials = Credentials.create(privateKey);
    final byte[] encodedMessage =
            PrivateTransactionEncoder.signMessage(rawTransaction, credentials);
    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());
    assertTrue(result instanceof SignedRawPrivateTransaction);
    final SignedRawPrivateTransaction signedResult = (SignedRawPrivateTransaction) result;
    assertNotNull(signedResult.getSignatureData());
    Sign.SignatureData signatureData = signedResult.getSignatureData();
    final byte[] encodedTransaction = PrivateTransactionEncoder.encode(rawTransaction);
    final BigInteger key = Sign.signedMessageToKey(encodedTransaction, signatureData);
    assertEquals(key, credentials.getEcKeyPair().getPublicKey());
    assertEquals(credentials.getAddress(), signedResult.getFrom());
    signedResult.verify(credentials.getAddress());
    assertNull(signedResult.getChainId());
}
 
Example 20
Source File: ProposalContractTest.java    From client-sdk-java with Apache License 2.0 3 votes vote down vote up
@Before
public void init() throws Exception {

	superCredentials = Credentials.create("0xa689f0879f53710e9e0c1025af410a530d6381eebb5916773195326e123b822b");
	System.out.println("superCredentials balance="+ web3j.platonGetBalance(superCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance());
	
	stakingCredentials = Credentials.create("0x690a32ceb7eab4131f7be318c1672d3b9b2dadeacba20b99432a7847c1e926e0");
	System.out.println("stakingCredentials balance="+ web3j.platonGetBalance(stakingCredentials.getAddress(), DefaultBlockParameterName.LATEST).send().getBalance());
	
	voteCredentials = superCredentials;
	
    proposalContract = ProposalContract.load(web3j, stakingCredentials, chainId);
}