Java Code Examples for org.web3j.crypto.WalletUtils#loadCredentials()

The following examples show how to use org.web3j.crypto.WalletUtils#loadCredentials() . 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: Template.java    From tutorials with MIT License 6 votes vote down vote up
private void deployContract() throws Exception{

        Web3j web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/<your_token>"));

        Credentials credentials =
            WalletUtils.loadCredentials(
               "<password>",
               "/path/to/<walletfile>");

        Greeting contract = Greeting.deploy(
            web3j, credentials,
            ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT,
            "Hello blockchain world!").send();

        String contractAddress = contract.getContractAddress();
        l.debug("Smart contract deployed to address "+ contractAddress);

        l.debug("Value stored in remote smart contract: "+ contract.greet().send());

        TransactionReceipt transactionReceipt = contract.setGreeting("Well hello again").send();

        l.debug("New value stored in remote smart contract: "+ contract.greet().send());
    }
 
Example 2
Source File: Web3Service.java    From tutorials with MIT License 6 votes vote down vote up
public String fromScratchContractExample() {

        String contractAddress = "";

        try {
            //Create a wallet
            WalletUtils.generateNewWalletFile("PASSWORD", new File("/path/to/destination"), true);
            //Load the credentials from it
            Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile");

            //Deploy contract to address specified by wallet
            Example contract = Example.deploy(this.web3j,
                    credentials,
                    ManagedTransaction.GAS_PRICE,
                    Contract.GAS_LIMIT).send();

            //Het the address
            contractAddress = contract.getContractAddress();

        } catch (Exception ex) {
            System.out.println(PLEASE_SUPPLY_REAL_DATA);
            return PLEASE_SUPPLY_REAL_DATA;
        }
        return contractAddress;
    }
 
Example 3
Source File: PayWagesTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addEmployee() throws Exception {
	// Only personnel can add employee
	Credentials personnel = WalletUtils.loadCredentials(walletPwd, personnelWallet);
	transactionManager = new RawTransactionManager(web3j, personnel, chainId);
	PayWages payWages = PayWages.load(contractAddress, web3j, transactionManager, gasProvider);
	System.err.println("msg.sender >>>> " + transactionManager.getFromAddress());
	System.err.println("contract personnel address >>> " + payWages.personnel().send());

	// invoke function
	BigInteger id = BigInteger.valueOf(123456L);
	// status:0-invalid,1-valid
	BigInteger status = BigInteger.valueOf(1L);
	String name = "Alice";
	TransactionReceipt transactionReceipt = payWages.addEmployee(id, status, name, employeeAddress).send();
	System.err.println("transactionReceipt status >>>> " + transactionReceipt.getStatus());
	System.err.println("gasUsed >>>> " + transactionReceipt.getGasUsed().toString());
	System.err.println("transactionReceipt >>>> " + JSON.toJSONString(transactionReceipt));

	// get Event
	List<AddUserEventResponse> list = payWages.getAddUserEvents(transactionReceipt);
	System.err.println("code >>> " + list.get(0)._code);
	System.err.println("address >>> " + list.get(0)._account);
	System.err.println("AddUserEventResponse >>> " + JSON.toJSONString(list));
}
 
Example 4
Source File: PayWagesTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void pay() throws Exception {
	Credentials financer = WalletUtils.loadCredentials(walletPwd, financerWallet);
	transactionManager = new RawTransactionManager(web3j, financer, chainId);
	PayWages payWages = PayWages.load(contractAddress, web3j, transactionManager, gasProvider);

	BigInteger balance = payWages.getContractBalance().send();
	System.err.println("Before pay, ContractBalance >>>> " + balance);

	BigInteger amout = Convert.toVon(BigDecimal.valueOf(18), Convert.Unit.LAT).toBigInteger();
	TransactionReceipt receipt = payWages.pay(employeeAddress, amout).send();
	System.err.println("pay status >>>> " + receipt.getStatus());
	System.err.println("receipt >>>> " + JSON.toJSONString(receipt));

	balance = payWages.getContractBalance().send();
	System.err.println("After pay, ContractBalance >>>> " + balance);
}
 
Example 5
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void restoreWalletFromFile(String walletPath, String pass, WalletCreationCallback callback) {
    Credentials credentials = null;
    try {
        credentials = WalletUtils.loadCredentials(pass, walletPath);
    } catch (IOException | CipherException e) {
        e.printStackTrace();
    }

    if (credentials != null) {
        ECKeyPair keyPair = credentials.getEcKeyPair();
        WalletCreationTask task = new WalletCreationTask(callback, keyPair);
        task.execute(pass);
    }
}
 
Example 6
Source File: PaperWallet.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
public Credentials getCredentials(String passPhrase) throws Exception {
	if (credentials != null) {
		return credentials;
	}

	try {
		String fileWithPath = getFile().getAbsolutePath();
		credentials = WalletUtils.loadCredentials(passPhrase, fileWithPath);

		return credentials;
	}
	catch (Exception e) {
		throw new Exception ("Failed to access credentials in file '" + getFile().getAbsolutePath() + "'", e);
	}
}
 
Example 7
Source File: PaperWallet.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
public PaperWallet(String passPhrase, File walletFile) {
	// check if provided file exists
	if(!walletFile.exists() || walletFile.isDirectory()) { 
		System.err.println(String.format("%s file does not exist or is a directory", WALLET_ERROR));
	}
	
	try {
		credentials = WalletUtils.loadCredentials(passPhrase, walletFile);
	} 
	catch (Exception e) {
		System.err.println(String.format("%s failed to load credentials with provided password", WALLET_ERROR));
	}
}
 
Example 8
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void restoreWalletFromFile(String walletPath, String pass, WalletCreationCallback callback) {
    Credentials credentials = null;
    try {
        credentials = WalletUtils.loadCredentials(pass, walletPath);
    } catch (IOException | CipherException e) {
        e.printStackTrace();
    }

    if (credentials != null) {
        ECKeyPair keyPair = credentials.getEcKeyPair();
        WalletCreationTask task = new WalletCreationTask(callback, keyPair);
        task.execute(pass);
    }
}
 
Example 9
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void restoreWalletFromFile(String walletPath, String pass, WalletCreationCallback callback) {
    Credentials credentials = null;
    try {
        credentials = WalletUtils.loadCredentials(pass, walletPath);
    } catch (IOException | CipherException e) {
        e.printStackTrace();
    }

    if (credentials != null) {
        ECKeyPair keyPair = credentials.getEcKeyPair();
        WalletCreationTask task = new WalletCreationTask(callback, keyPair);
        task.execute(pass);
    }
}
 
Example 10
Source File: EthQueryExecutor.java    From eth-jdbc-connector with Apache License 2.0 5 votes vote down vote up
private Credentials getCredential() {
    if (properties == null || !properties.containsKey(DriverConstants.KEYSTORE_PASSWORD)
            || !properties.containsKey(DriverConstants.KEYSTORE_PATH)) {
        throw new BlkchnException(
                "Query needs keystore path and password, passed as Properties while creating connection");
    }
    try {
        return WalletUtils.loadCredentials(properties.getProperty(DriverConstants.KEYSTORE_PASSWORD),
                properties.getProperty(DriverConstants.KEYSTORE_PATH));
    } catch (Exception e) {
        throw new BlkchnException("Check your KEYSTORE credentials ", e);
    }
}
 
Example 11
Source File: PayWagesTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getBalance() throws Exception {
	Credentials financer = WalletUtils.loadCredentials(walletPwd, financerWallet);
	transactionManager = new RawTransactionManager(web3j, financer, chainId);
	PayWages payWages = PayWages.load(contractAddress, web3j, transactionManager, gasProvider);
	BigInteger balance = payWages.getTotalBalance().send();
	System.err.println("TotalBalance >>>> " + balance);

	balance = payWages.getContractBalance().send();
	System.err.println("ContractBalance >>>> " + balance);
}
 
Example 12
Source File: EthSignerTestHarnessFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
public static EthSignerTestHarness create(
    final Path tempDir, final String keyPath, final Integer besuPort, final long chainId)
    throws IOException, CipherException {

  final Path keyFilePath = copyResource(keyPath, tempDir.resolve(keyPath));

  final EthSignerConfig config =
      new EthSignerConfig(
          Level.DEBUG,
          HOST,
          besuPort,
          Duration.ofSeconds(10),
          HOST,
          0,
          new ConfigurationChainId(chainId),
          tempDir);

  final EthSigner ethSigner =
      new EthSigner(
          config,
          new SingleTransactionSignerProvider(
              new CredentialTransactionSigner(
                  WalletUtils.loadCredentials("", keyFilePath.toAbsolutePath().toFile()))));
  ethSigner.run();

  waitForPortFile(tempDir);

  LOG.info("EthSigner port: {}", config.getHttpListenPort());

  return new EthSignerTestHarness(config, loadPortsFile(tempDir));
}
 
Example 13
Source File: IntegrationTestBase.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
static void setupEthSigner(final long chainId, final String downstreamHttpRequestPath)
    throws IOException, CipherException {
  clientAndServer = startClientAndServer();

  final File keyFile = createKeyFile();
  final File passwordFile = createFile("password");
  credentials = WalletUtils.loadCredentials("password", keyFile);

  final TransactionSignerProvider transactionSignerProvider =
      new SingleTransactionSignerProvider(transactionSigner(keyFile, passwordFile));

  final HttpClientOptions httpClientOptions = new HttpClientOptions();
  httpClientOptions.setDefaultHost(LOCALHOST);
  httpClientOptions.setDefaultPort(clientAndServer.getLocalPort());

  final HttpServerOptions httpServerOptions = new HttpServerOptions();
  httpServerOptions.setPort(0);
  httpServerOptions.setHost("localhost");

  // Force TransactionDeserialisation to fail
  final ObjectMapper jsonObjectMapper = new ObjectMapper();
  jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, true);
  jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);

  final JsonDecoder jsonDecoder = new JsonDecoder(jsonObjectMapper);

  vertx = Vertx.vertx();
  runner =
      new Runner(
          chainId,
          transactionSignerProvider,
          httpClientOptions,
          httpServerOptions,
          downstreamTimeout,
          new DownstreamPathCalculator(downstreamHttpRequestPath),
          jsonDecoder,
          dataPath,
          vertx,
          singletonList("sample.com"));
  runner.start();

  final Path portsFile = dataPath.resolve(PORTS_FILENAME);
  waitForNonEmptyFileToExist(portsFile);
  final int ethSignerPort = httpJsonRpcPort(portsFile);
  RestAssured.port = ethSignerPort;

  LOG.info(
      "Started ethSigner on port {}, eth stub node on port {}",
      ethSignerPort,
      clientAndServer.getLocalPort());

  unlockedAccount =
      transactionSignerProvider.availableAddresses().stream().findAny().orElseThrow();
}
 
Example 14
Source File: EthereumAuth.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public EthereumAuth(String walletPassword,
                    String walletFilePath) throws Exception {
    walletCredentials = WalletUtils.loadCredentials(walletPassword,
                                                    walletFilePath);
}
 
Example 15
Source File: EthereumAuth.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public EthereumAuth(String walletPassword,
                    File wallet) throws Exception {
    walletCredentials = WalletUtils.loadCredentials(walletPassword,
                                                    wallet);
}
 
Example 16
Source File: EthereumAuth.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public EthereumAuth(String walletPassword,
                    String walletFileName,
                    ClassLoader classLoader) throws Exception {
    walletCredentials = WalletUtils.loadCredentials(walletPassword,
                                                    EthereumUtils.createTmpFile(classLoader.getResourceAsStream(walletFileName)));
}
 
Example 17
Source File: WalletStorage.java    From Lunary-Ethereum-Wallet with GNU General Public License v3.0 4 votes vote down vote up
public Credentials getFullWallet(Context context, String password, String wallet) throws IOException, JSONException, CipherException {
    if (wallet.startsWith("0x"))
        wallet = wallet.substring(2, wallet.length());
    return WalletUtils.loadCredentials(password, new File(context.getFilesDir(), wallet));
}
 
Example 18
Source File: WalletStorage.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
public Credentials getFullWallet(Context context, String password, String wallet) throws IOException, JSONException, CipherException {
    if (wallet.startsWith("0x"))
        wallet = wallet.substring(2, wallet.length());
    return WalletUtils.loadCredentials(password, new File(context.getFilesDir(), wallet));
}