org.web3j.crypto.WalletUtils Java Examples

The following examples show how to use org.web3j.crypto.WalletUtils. 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: CreateTransactionInteract.java    From Upchain-wallet with GNU Affero General Public License v3.0 7 votes vote down vote up
public Single<String>  createEthTransaction(ETHWallet from,  String to, BigInteger amount, BigInteger gasPrice, BigInteger gasLimit, String password) {
    final Web3j web3j = Web3j.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl));

    return networkRepository.getLastTransactionNonce(web3j, from.address)
            .flatMap(nonce -> Single.fromCallable( () -> {

        Credentials credentials = WalletUtils.loadCredentials(password,  from.getKeystorePath());
        RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, amount);
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);

        String hexValue = Numeric.toHexString(signedMessage);
        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();

        return ethSendTransaction.getTransactionHash();

    } ).subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread()));
}
 
Example #2
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 #3
Source File: RegisterParamsTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
void eth1EncryptedKeystoreReturnsCredential(@TempDir final Path tempDir)
    throws IOException, CipherException {
  // create v3 wallet
  final String keystoreFileName =
      WalletUtils.generateWalletFile(PASSWORD, EXPECTED_EC_KEYPAIR, tempDir.toFile(), true);
  final File keystoreFile = tempDir.resolve(keystoreFileName).toFile();
  // create password file
  final File passwordFile =
      Files.writeString(tempDir.resolve("password.txt"), "test123").toFile();

  final Eth1PrivateKeyOptions.Eth1EncryptedKeystoreOptions keystoreOptions =
      new Eth1PrivateKeyOptions.Eth1EncryptedKeystoreOptions();
  keystoreOptions.eth1KeystoreFile = keystoreFile;
  keystoreOptions.eth1KeystorePasswordFile = passwordFile;

  final Eth1PrivateKeyOptions eth1PrivateKeyOptions = new Eth1PrivateKeyOptions();
  eth1PrivateKeyOptions.keystoreOptions = keystoreOptions;

  final RegisterParams registerParams =
      new RegisterParams(commandSpec, eth1PrivateKeyOptions, SHUTDOWN_FUNCTION, consoleAdapter);
  final Credentials eth1Credentials = registerParams.getEth1Credentials();
  assertThat(eth1Credentials.getEcKeyPair()).isEqualTo(EXPECTED_EC_KEYPAIR);
}
 
Example #4
Source File: EnsResolver.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Reverse name resolution as documented in the
 * <a href="https://docs.ens.domains/en/latest/userguide.html#reverse-name-resolution">specification</a>.
 * @param address an ethereum address, example: "0x314159265dd8dbb310642f98f50c066173c1259b"
 * @return a EnsName registered for provided address
 */
public String reverseResolve(String address) {
    if (WalletUtils.isValidAddress(address)) {
        String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
        PublicResolver resolver = obtainPublicResolver(reverseName);

        byte[] nameHash = NameHash.nameHashAsBytes(reverseName);
        String name = null;
        try {
            name = resolver.name(nameHash).send();
        } catch (Exception e) {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!isValidEnsName(name)) {
            throw new RuntimeException("Unable to resolve name for address: " + address);
        } else {
            return name;
        }
    } else {
        throw new EnsResolutionException("Address is invalid: " + address);
    }
}
 
Example #5
Source File: EnsResolver.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
public String resolve(String contractId) {
    if (isValidEnsName(contractId)) {
        PublicResolver resolver = obtainPublicResolver(contractId);

        byte[] nameHash = NameHash.nameHashAsBytes(contractId);
        String contractAddress = null;
        try {
            contractAddress = resolver.addr(nameHash).send();
        } catch (Exception e) {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!WalletUtils.isValidAddress(contractAddress)) {
            throw new RuntimeException("Unable to resolve address for name: " + contractId);
        } else {
            return contractAddress;
        }
    } else {
        return contractId;
    }
}
 
Example #6
Source File: KeyImporter.java    From etherscan-explorer with GNU General Public License v3.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 #7
Source File: TokensRealmSource.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public Single<Token> saveTicker(Wallet wallet, final Token token) {
    return Single.fromCallable(() -> {
        if (!WalletUtils.isValidAddress(wallet.address)
                || token.ticker == null) return token;

        try (Realm realm = realmManager.getRealmInstance(wallet))
        {
            TransactionsRealmCache.addRealm();
            realm.beginTransaction();
            writeTickerToRealm(realm, token);
            realm.commitTransaction();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return token;
    });
}
 
Example #8
Source File: TokensRealmSource.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public Single<Token[]> saveTickers(Wallet wallet, Token[] tokens)
{
    return Single.fromCallable(() -> {
        try (Realm realm = realmManager.getRealmInstance(wallet))
        {
            TransactionsRealmCache.addRealm();
            realm.beginTransaction();
            for (Token token : tokens)
            {
                if (!WalletUtils.isValidAddress(wallet.address)
                        || token.ticker == null) continue;
                writeTickerToRealm(realm, token);
            }
            realm.commitTransaction();
            TransactionsRealmCache.subRealm();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return tokens;
    });
}
 
Example #9
Source File: ImportWalletActivity.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public void onKeystore(String keystore, String password)
{
    String address = extractAddressFromStore(keystore);
    if (address != null && WalletUtils.isValidAddress(address))
    {
        onProgress(true);
        importWalletViewModel.checkKeystorePassword(keystore, address, password)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> keyStoreValid(result, address)).isDisposed();
    }
    else
    {
        keyImportError(getString(R.string.invalid_keystore));
    }
}
 
Example #10
Source File: ImportWalletActivity.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@Override
public void onPrivateKey(String privateKey)
{
    try
    {
        BigInteger key = new BigInteger(privateKey, 16);
        if (!WalletUtils.isValidPrivateKey(privateKey)) throw new Exception(getString(R.string.invalid_private_key));
        ECKeyPair keypair = ECKeyPair.create(key);
        String address = Numeric.prependHexPrefix(Keys.getAddress(keypair));

        if (importWalletViewModel.keystoreExists(address))
        {
            queryReplaceWalletPrivateKey(address);
        }
        else
        {
            importWalletViewModel.importPrivateKeyWallet(address, this, this);
        }
    }
    catch (Exception e)
    {
        keyImportError(e.getMessage());
    }
}
 
Example #11
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 #12
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 #13
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 #14
Source File: EnsResolver.java    From web3j with Apache License 2.0 6 votes vote down vote up
public String resolve(String contractId) {
    if (isValidEnsName(contractId, addressLength)) {
        PublicResolver resolver = obtainPublicResolver(contractId);

        byte[] nameHash = NameHash.nameHashAsBytes(contractId);
        String contractAddress = null;
        try {
            contractAddress = resolver.addr(nameHash).send();
        } catch (Exception e) {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!WalletUtils.isValidAddress(contractAddress)) {
            throw new RuntimeException("Unable to resolve address for name: " + contractId);
        } else {
            return contractAddress;
        }
    } else {
        return contractId;
    }
}
 
Example #15
Source File: EnsResolver.java    From web3j with Apache License 2.0 6 votes vote down vote up
/**
 * Reverse name resolution as documented in the <a
 * href="https://docs.ens.domains/contract-api-reference/reverseregistrar">specification</a>.
 *
 * @param address an ethereum address, example: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"
 * @return a EnsName registered for provided address
 */
public String reverseResolve(String address) {
    if (WalletUtils.isValidAddress(address, addressLength)) {
        String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
        PublicResolver resolver = obtainPublicResolver(reverseName);

        byte[] nameHash = NameHash.nameHashAsBytes(reverseName);
        String name;
        try {
            name = resolver.name(nameHash).send();
        } catch (Exception e) {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!isValidEnsName(name, addressLength)) {
            throw new RuntimeException("Unable to resolve name for address: " + address);
        } else {
            return name;
        }
    } else {
        throw new EnsResolutionException("Address is invalid: " + address);
    }
}
 
Example #16
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 #17
Source File: StringUtil.java    From dapp-wallet-demo with Apache License 2.0 5 votes vote down vote up
public static String shortAddress(String address){
    String shortOfAddress = "unknown";
    if (WalletUtils.isValidAddress(address)){
        int length = address.length();
        shortOfAddress = address.substring(0,10) + "..." + address.substring(length-10,length);
    }
    return shortOfAddress;
}
 
Example #18
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 #19
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 #20
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void saveJsonLight() {
    try {
        BigInteger b = new BigInteger(Coders.decodeBase64(sharedManager.getLastSyncedBlock()), 16);
        String filename1 = WalletUtils.generateWalletFile("", ECKeyPair.create(b), com.google.common.io.Files.createTempDir(), false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #21
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 #22
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public void saveJsonLight() {
    try {
        BigInteger b = new BigInteger(Coders.decodeBase64(sharedManager.getLastSyncedBlock()), 16);
        String filename1 = WalletUtils.generateWalletFile("", ECKeyPair.create(b), com.google.common.io.Files.createTempDir(), false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #23
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 #24
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 #25
Source File: EnsResolver.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
/**
 * Reverse name resolution as documented in the <a
 * href="https://docs.ens.domains/contract-api-reference/reverseregistrar">specification</a>.
 *
 * @param address an ethereum address, example: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"
 * @return a EnsName registered for provided address
 */
public String reverseResolve(String address) throws UnableToResolveENS
{
    String name = null;
    if (WalletUtils.isValidAddress(address))
    {
        String reverseName = Numeric.cleanHexPrefix(address) + REVERSE_NAME_SUFFIX;
        try
        {
            String resolverAddress = lookupResolver(reverseName);
            byte[] nameHash = NameHash.nameHashAsBytes(reverseName);
            name = getContractData(EthereumNetworkBase.MAINNET_ID, resolverAddress, getName(nameHash));
        }
        catch (Exception e)
        {
            throw new RuntimeException("Unable to execute Ethereum request", e);
        }

        if (!isValidEnsName(name, addressLength))
        {
            throw new UnableToResolveENS("Unable to resolve name for address: " + address);
        }
        else
        {
            return name;
        }
    }
    else
    {
        throw new EnsResolutionException("Address is invalid: " + address);
    }
}
 
Example #26
Source File: PaperWallet.java    From ethereum-paper-wallet with Apache License 2.0 5 votes vote down vote up
public PaperWallet(String passPhrase, String pathToFile) throws Exception {
	this.passPhrase = setPassPhrase(passPhrase);
	this.pathToFile = setPathToFile(pathToFile);

	try {
		fileName = WalletUtils.generateNewWalletFile(this.passPhrase, new File(this.pathToFile));
		credentials = getCredentials(this.passPhrase);
	}
	catch (Exception e) {
		throw new Exception("Failed to create account", e);
	}
}
 
Example #27
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 #28
Source File: TokensRealmSource.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void saveToken(Wallet wallet, Token token, Date currentTime) {
    if (!WalletUtils.isValidAddress(wallet.address)) return;
    try (Realm realm = realmManager.getRealmInstance(wallet))
    {
        TransactionsRealmCache.addRealm();
        realm.beginTransaction();
        saveToken(realm, token);
        realm.commitTransaction();
        TransactionsRealmCache.subRealm();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
 
Example #29
Source File: Default.java    From Android-Wallet-Token-ERC20 with Apache License 2.0 5 votes vote down vote up
public String Generation(File keystoreWallet, String passwordWallet){
    try {
        return WalletUtils.generateNewWalletFile(passwordWallet, keystoreWallet, false);
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return null;
}
 
Example #30
Source File: HomeActivity.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void onBackup(String address)
{
    if (address != null && WalletUtils.isValidAddress(address))
    {
        Toast.makeText(this, getString(R.string.postponed_backup_warning), Toast.LENGTH_LONG).show();
    }
}