Develop a Secure Blockchain App


Objective

Learn how to create your own Decentralized Applications (DApp) using Samsung Blockchain Keystore SDK.

Overview

Integrating with new technology like Blockchain is a burden to most developers. For this reason, we offer a way to interwork with Samsung Blockchain Keystore SDK with less effort. Developers can easily become a DApp developer with our Samsung Blockchain Keystore SDK.

Decentralized Applications (DApps) run and store data on the Blockchain network instead of a central server. DApps offer increased security and reliability compared to centralized applications. Moreover, it provides a simple method for in-app payments using cryptocurrency.

Samsung Blockchain Keystore SDK is used to obtain account information and sign a transaction to transfer cryptocurrency or execute smart contract execution.

In this Code Lab, you can learn how to integrate Samsung Blockchain Keystore SDK into your app and how to implement Blockchain basic concepts such as account information and signing transactions.

Set up your environment

You will need the following:

  • Java SE Development Kit 8 or later
  • Android Studio (latest version recommended)
  • Mobile phone which supports Samsung Blockchain

Sample Code

Here is a sample code for you to start coding in this Code Lab. Download it and start your learning experience!

Keystore SDK Sample Code
(1.03 MB)

Enable Developer Mode

The Developer Mode helps developers test the Samsung Blockchain Keystore. In developer mode, App ID verification is bypassed, so Samsung Blockchain Keystore APIs will be enabled. Developers can activate developer mode by following the steps below.

  1. Go to Samsung Blockchain Keystore Device > Settings > Biometrics and security > Samsung Blockchain Keystore

  2. General > About Blockchain Keystore

  3. Tap the Samsung Blockchain Keystore area quickly 10 times or more

  4. If succeeded, (Developer Mode) will be shown before the version and it means developer mode has been activated

  5. Now you can test your app with Samsung Blockchain Keystore

Open project file

After downloading the sample code, open the given Android application project. This project is a simple comments DApp based on Ethereum Ropsten test network. It retrieves comments data from smart contract, displays them on the screen, and makes a transaction to execute smart contract function to post user’s comment.

In the next steps, you can get an account address and execute DApp service with Blockchain Keystore and you can see the result of successful DApp execution.

Set the app ID

Here, you don’t need to set the application ID to use Samsung Blockchain Keystore SDK. Instead, you must enable developer mode as described previously.

For the release version of your Android app, in your Android Manifest file, add a metadata with a name as scw_app_id and a value as the App ID issued by Samsung Blockchain Keystore team. Samsung Blockchain Keystore aar file will read this value when your Android app is initialized and help your Android app connect to Samsung Blockchain Keystore:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.samsung.android.sdk.coldwallet.test"
        android:versionCode="1"
        android:versionName="1.0">
    <application>
        <meta-data android:name="scw_app_id"
                   android:value= <!-- PUT YOUR APP ID HERE --> />
    </application>
</manifest>

Import Samsung Blockchain Keystore SDK library into the project

The SDK library is located at aar/KeystoreSDK_v1.1.0.aar of the project file. To import the library go to Gradle Scripts > build.gradle and enter the following dependencies:


dependencies {
    repositories {
            flatDir{
                dirs 'aar'
            }
    }
    
    implementation 'com.samsung.android.sdk.coldwallet:KeystoreSDK_v1.1.0@aar'
}

Check the status of Samsung Blockchain Keystore

The first thing to do is to check the status of Samsung Blockchain Keystore. In the sample application, it is implemented at initializeKeystore() in presenter IntroPresenter.java. You can find the following steps to check the status of Keystore.

  1. In your Android app, call ScwService.getInstance(). If the returned value is an instance and not null, then it means Samsung Blockchain Keystore is supported on the device. However, if null is returned, the user must use a different keystore. In the sample code, toast a message to notify that the device doesn’t support the keystore.

    
    // Check Samsung blockchain keystore is supported or not.
    if (ScwService.getInstance() == null) {
        mContract.toastMessage("Samsung blockchain Keystore is not supported on your device.");
        return false;
    }
    
    
  2. Call getKeystoreApiLevel API to see if the current Samsung Blockchain Keystore being used, properly supports the features that your Android app is currently aiming for. If the required API level is higher than the current Samsung Blockchain Keystore level, users are directed to Samsung Blockchain Keystore app page in Galaxy Store through the provided deeplink to update.

    
     // check installed api level
    else if (ScwService.getInstance().getKeystoreApiLevel() < 1) {
        // if api level is lower, jump to galaxy apps to update keystore app.
        mContract.showDialog(""
            , "OK"
            , "The api level is too low. Jump to galaxy store"
            , () -> mContract.launchDeepLink(ScwDeepLink.GALAXY_STORE));
    }
    
    
  3. Check if a user has set up the Samsung Blockchain Keystore and is ready to use it by calling getSeedHash API. If the Seed Hash value in string is zero-length, this means the user has not set up Samsung Blockchain Keystore yet. Hence, your app will need to guide the user to jump to Samsung Blockchain Keystore via deeplink to either create or import a wallet.

    
    // check seed hash exist.
    else if (ScwService.getInstance().getSeedHash().length() == 0) {
        // if seed hash is empty,
        // jump to blockchain keystore to create or import wallet
        mContract.showDialog(""
            , "OK"
            , "The seed hash is empty." +
                "Jump to blockchain keystore to create/import wallet."
            , () -> mContract.launchDeepLink(ScwDeepLink.MAIN));
    }
    
    
  4. If the getSeedHash API returned value is not zero-length, it means that the user has successfully set up Samsung Blockchain Keystore. If there is a previously saved or cached Seed Hash value, compare the two Seed Hash values. If those two values are not equal, nor if there is no such saved cached Seed Hash value, then the address has to be checked again. If the Seed Hash value has been changed, it means the Master Seed has been changed as well, meaning the address that your Android app was linked to may no longer be the same address.

    
    // check seed hash cached
    else if (!TextUtils.equals(cachedSeedHash, ScwService.getInstance().getSeedHash())) {
        // if the seed hash is different from cached, update seed hash and address
        // if success, go to next activity.
        final String ethereumHdPath = "m/44'/60'/0'/0/0";
        getEthereumAddress(ethereumHdPath
                , (success, errorCode, address, seedHash) -> {
            if (success) {
                updateAddress(address);
                updateSeedHash(seedHash);
                mContract.showTimelineActivity(true);
            } else {
                mContract.toastMessage("Cannot get address. error:" + errorCode);
            }
        });
    } 
    
    
  5. If those two values are equal, it means checking the Keystore status was successful, and you can move on to the next step.

    
    // success
    else {
        // set address from cached value
        // go to next activity
        String address = PrefsHelper.getInstance().getCachedAddress();
    
        updateSeedHash(cachedSeedHash);
        updateAddress(address);
        mContract.showTimelineActivity(false);
    } 
    
    

Get the Ethereum address

In the Blockchain network, the address can be used like a user’s account as the balance and the transaction history can be checked using the address. In this sample project, get the address from Keystore and display the address and account balance in the bottom sheet of the screen. Keystore is a Hierarchical Deterministic (HD) Wallet, a standard tree structure represented by derivation paths. For the Ethereum address, use “m/44'/60'/0'/0/0” follow BIP44.

It is implemented at getEthereumAddress(String hdpath, GetEthereumAddressCallback callback) in presenter/IntroPresenter.java:


ArrayList<String> path = new ArrayList<>();
path.add(hdpath);
ScwService.getInstance().getAddressList(new ScwService.ScwGetAddressListCallback() {
    @Override
    public void onSuccess(List<String> list) {
        String seedHash = ScwService.getInstance().getSeedHash();
        String address = list.get(0);
        callback.OnAddressReceived(true, 0, address, seedHash);
    }
 
    @Override
    public void onFailure(int errorCode) {
        callback.OnAddressReceived(false, errorCode, "", "");
    }
}, path); 

Sign a transaction

Ether value transfer or smart contract execution is executed by transactions that users create and sign. Signing a transaction is the process of generating a signature on it using the private key of the transaction sender.

Samsung Blockchain Keystore can be utilized to sign a cryptocurrency transaction, such as Ethereum by implementing the following steps:

  1. Creates an unsigned transaction, and requests Samsung Blockchain Keystore to sign the transaction via APIs like signEthTransaction.
  2. Then the user will see a transaction confirmation page on a secure screen called, Trusted User Interface (TUI) executed in Trusted Execution Environment (TEE) by Samsung Blockchain Keystore.
  3. Once the user confirms the transaction with PIN or Biometrics Authentication, like fingerprint, Samsung Blockchain Keystore will sign a transaction with the private key derived from the given HD Path.
  4. When Samsung Blockchain Keystore returns the signed transaction, your app can submit or send the signed transaction to the Blockchain network.

In this sample project, create an unsigned transaction to execute posting a comment smart contract. In addition, sign the transaction with Keystore and send the transaction.

It is implemented at signTransaction() in presenter/WriteFeedPresenter.java:


// Sign the transaction with Samsung blockchain keystore
// Use HDPath m/44'/60'/0'/0/0
final String HDPath = "m/44'/60'/0'/0/0";
 
ScwService.getInstance().signEthTransaction(
    new ScwService.ScwSignEthTransactionCallback() {
        @Override
        public void onSuccess(byte[] signedTransaction) {
            boolean result = sendSignedTransaction(signedTransaction);
            listener.transactionDidFinish(result, "");
        }

        @Override
        public void onFailure(int errorCode) {
            listener.transactionDidFinish(false, "Error code : " + errorCode);
        }
    }, unsignedTx, HDPath);
    

Run the app and try it out. The app screen should look like below.

You're done!

Congratulations! You have successfully achieved the goal of this Code Lab. Now, you can create a decentralized app by yourself! If you're having trouble, you may download this file:

Keystore SDK Complete Code
(886.34 KB)