Quantcast
Jump to content

Optimize Address Fetching in the Samsung Blockchain Keystore SDK with Seed Hash


STF News
 Share

Recommended Posts

2020-01-20-01-banner.png

Last June, Samsung introduced Samsung Blockchain Keystore (SBK), a secure built-in cold wallet in Galaxy devices. The cold wallet is isolated with Samsung Knox and encapsulated within a defense-grade Trusted Execution Environment (TEE). The Samsung Blockchain Keystore SDK enables use of this wallet in Android applications.

In this article, we discuss how to optimize the address fetching process with seed hash. Fetching addresses from the Samsung Blockchain Keystore using the SDK is time-consuming, so this blog will help you learn how to store your seed hash values to avoid delays in fetching information whenever you launch your app.

The Samsung Blockchain Keystore (SBK) SDK enables users to get blockchain public addresses from the Samsung Blockchain Keystore and sign a cryptocurrency transaction to authenticate. A public address is the hashed version of the public key and is used to recognize a blockchain cryptocurrency account. As the blockchain protocol goes, anyone can fetch the balance and transaction history of an account with its public address.

Developers can invoke the getAddressList() API of the SBK SDK to fetch the address list. Every time this API is called with the same request, you get the same address list. A change to the list occurs only when the wallet's root seed has been changed. The Programming Guide: API Flow and Use Cases provides more detailed information.

Seed hash

The SDK uses the term Seed Hash (see Figure 1, inside the green rectangle).

Figure 1 Figure 1: SBK SDK API flow and use case

The SDK Glossary says:

Seed Hash: A pseudo seed hash that is generated randomly when the HD wallet is created. If the master seed of a wallet is changed, the seed hash will be changed as well.

The getSeedHash() API gets the current seed hash from the Samsung Blockchain Keystore. Fetching the address list from the Samsung Blockchain Keystore using the SBK SDK initiates an expensive operation that requires a considerable amount of time. To provide the user with a seamless experience, the SBK SDK programming guide recommends that developers store information from the getSeedHash() API. Developers then need to invoke the getAddressList() API only when the stored seed hash is different from the seed hash fetched using the SBK SDK.

Prerequisites

Before you begin, be sure you've met these prerequisites:

Store the seed hash

I recommend using Android SharedPreferences to store the seed hash. Remember, the seed hash value is not sensitive data; it's not the wallet's root seed itself. It's a hash value generated to keep track of change in the wallet. Because high-level security is not a concern, and when you have a relatively small collection of key values that you'd like to save, SharedPreferences is an easily implemented solution.

All you need to do is get the SharedPreferences file and then read and write key-value pairs on it. If you prefer another method of storing data, you can select any one of the methods described in the Android: Data and file storage overview.

The following code snippet refers to SharedPreferences:

private static final String seedHashKey = "seed\_hash";
private static final String defaultSeedHashValue = "";
private static SharedPreferences mSharedPreference;

mSharedPreference = getActivity().getPreferences(Context.MODE\_PRIVATE);

public static String getSeedHash() {
    return mSharedPreferences.getString(
                                 seedHashKey, defaultSeedHashValue);
}
public static void setSeedHash(String seedHash) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString(seedHashKey, seedHash);
        editor.commit();
    }
}

//Fetch SeedHash from SBK and Store on Share Preference
String seedHashSDK = ScwService.getInstance().getSeedHash();
setSeedHash(seedHashSDK);

Get the address list from the Samsung Blockchain Keystore

The getAddressList() API of the SBK SDK requires the HD path list and callback function parameters.

  • HD path list parameter: An ArrayList, a list of strings in which every string denotes an HD path. See Understanding Keystore > Key Management for more information.
  • Callback function parameter: A callback function of type ScwService.ScwGetAddressListCallback. The address fetching method is performed asynchronously, once the completed onSuccess() or onFailure() method is invoked. onSuccess() holds the required address list as a List, whereas onFailure() holds the error code.

The following code snippet retrieves four addresses at one time:

private ScwService.ScwGetAddressListCallback mScwGetAddressListCallback =
new ScwService.ScwGetAddressListCallback() {
    @Override
    public void onSuccess(List<String> addressList) {
        Log.i(Util.LOG\_TAG,
                       "Accounts fetched from SDK Successfully.");
    }
    @Override
    public void onFailure(int errorCode) {
     // Error Codes Doc:
     // https://img-developer.samsung.com/onlinedocs/blockchain/keystore/
        Log.e(Util.LOG\_TAG,
              "Fetch Accounts Failure. Error Code: " + errorCode);
    }
};

public void getPublicAddress(ArrayList<String> hdPathList) {
    mScwService.getAddressList(
              mScwGetAddressListCallback, hdPathList);
}
ArrayList hdPathList = new ArrayList<>();
hdPathList.add(ScwService.getHdPath(ScwCoinType.ETH, 0));       //m/44'/60'/0'/0/0
hdPathList.add(ScwService.getHdPath(ScwCoinType.ETH, 1));       //m/44'/60'/0'/0/1
hdPathList.add(ScwService.getHdPath(ScwCoinType.ETH, 2));       //m/44'/60'/0'/0/2
hdPathList.add(ScwService.getHdPath(ScwCoinType.ETH, 3));       //m/44'/60'/0'/0/3

//  BTC -> "m/44'/0'/0'/0/0";

getPublicAddress(hdPathList);

Representation

For an Accounts info demonstration, I've used Android's RecyclerView. For detailed information, see Create a List with RecyclerView and this android recyclerview example.

Figure 1 Figure 1 Figure 2: Fetching an address list from the Samsung Blockchain Keystore

Store address information on an application database

Once you have fetched the required addresses from the Samsung Blockchain Keystore, design your mechanism to store this information. Let’s look at requirements at this stage:

  • Storage for account information: Accounts presented at app launch have to remain consistent on subsequent app launches, unless the wallet has been changed.
  • Provide users with a seamless experience: Information should not be fetched from Samsung Blockchain Keystore using SDK every time the app launches, because it causes delays.

This leads us to Android Room. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

The three major Room components are:

  • Database: Contains the database holder
  • Entity: Represents a table within the database.
  • DAO interface: Contains the methods used for accessing the database.

For more information about Android Room, see the documentation, blogs, and samples.

Database

Database class extends the RoomDatabase and builds the required database file.

@Database(entities = {AccountModel.class}, version = 1)
public abstract class AccountsDB extends RoomDatabase {

    private static AccountsDB accountsDB;
    public abstract IAccountsDAO iAccountsDAO();

    public static AccountsDB getInstance(Context context) {
        if (accountsDB == null || !accountsDB.isOpen()) {
            accountsDB = Room.databaseBuilder
                       (context, AccountsDB.class, Util.DB\_NAME)
                                                         .build();
        }
        return accountsDB;
    }
}

Entity

Here, we have declared our Model Class as a Room Entity using annotations. Room converts “the members of the class” to “columns of the table,” reducing boilerplate code.

@Entity
public class AccountModel {
    // accountID used as primary key & indexing, Auto Generated
    @PrimaryKey(autoGenerate = true)
    private int accountID;

    private String publicAddress;
    private String hdPath;
    // Getter & Setter Methods     
      .. ..
}

DAO interface

Here, you have to declare methods and corresponding database SQL queries to be run. This interface is implemented by the Room persistence library; corresponding codes are generated automatically to perform required database operations.

@Dao
public interface IAccountsDAO {
    @Query("SELECT \* FROM AccountModel")
    List<AccountModel> fetchAccounts();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAccounts(ArrayList<AccountModel> accountModels);

    @Query("DELETE FROM AccountModel")
    void removeAccounts();
}

On invoking the Java method, corresponding queries are performed on the database. For example, invoking the removeAccounts() method executes the DELETE FROM AccountModel query.

Database operations

Room doesn’t allow you to issue database queries on the main thread, as it can cause delays. Database CRUD operations must be performed on a separate thread.

I’ve used AsyncTask on this example to perform database operations. AsyncTask allows you to perform background operations and publish results on the UI thread without manipulating threads and/or handlers yourself. AsyncTask gives a high-level wrapper over multithreading, so you don't need expertise in concurrent threads or handlers.

  • doInBackground(Params...): Performs a computation on a background thread.
  • onPostExecute (result): Posts on the UI thread once doInBackground() operation is completed. The result parameter holds the execution result returned by doInBackground().
  • execute(Params...): On invocation, executes the task specified with given parameters.

See the API reference for details.

The following example code snippet shows the database retrieve data task:

private static class fetchAsyncTask extends
                   AsyncTask\> {
   @Override
   protected ArrayList<AccountModel> doInBackground(Void...voids){
       ArrayList<AccountModel> accountModels = new                 
           ArrayList<AccountModel>(accountsDB.iAccountsDAO().fetchAccounts());
        return accountModels;
    }

    @Override
    protected void onPostExecute   
                        (ArrayList<AccountModel> accountModels) {
        Log.i(Util.LOG\_TAG, "DB Fetch Successful");
        AccountRepository.setmAccountModels(accountModels);
    }
}

public static void fetchAccounts() {
    // DB CRUD operations has to be performed in a separate thread
    new fetchAsyncTask().execute();
}
Figure 4 Figure 3: Fetching an address list from database

Next steps

It's a lot of technical info for one blog. However, it will be worth it to have your apps launch quickly and seamlessly once you've optimized address fetching in the Samsung Blockchain Keystore SDK. For more detailed information, see the following references, and don't hesitate to reach out with any queries and feedback.

View the full blog at its source

Link to comment
Share on other sites

  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Popular Days

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Similar Topics

    • By Alex
      It’s that time of year again. You’ve got the biggest game in the NFL, and you’ve got your Samsung TV. All you need now is to know how to watch Super Bowl 2022 on your Samsung TV.
      If you’ve done any searching for a new big-screen to ring in Super Bowl 2022, one brand that we’re sure is dominating the ads of your browser is Samsung. Nestled comfortably in the top-five brands, Samsung Smart TVs are one of the best ways to experience any sporting event. Packed with industry-leading picture features and an intuitive streaming portal, you’ll be hard-pressed to beat the way the Super Bowl looks and feels on a Samsung set.
      If you’re all about the big game and want to know how you can watch it on that Samsung set you’re close to buying (or already own), we’ve put together this explainer to show you where and how you can catch Super Bowl 2022 through Samsung, and what settings you can use to maximize game. from the kickoff to the post-game celebration.
      This year’s Super Bowl takes place on February 13, 2022, with an expected kickoff time of 6:30 p.m. ET/3:30 p.m. PT. The annual event is taking place at SoFi Stadium in Los Angeles, with NBC holding the exclusive rights to all Super Bowl 2022 live and streamable coverage.
      How to watch Super Bowl 2022 on a Samsung TV
      Year to year, coverage rights to the Super Bowl are handled by the four main network-TV broadcasters — NBC, ABC, FOX, and CBS. In 2022, the golden contract rests in the hands of everyone’s rainbow-colored station, NBC. So what does this mean when it comes time to stream the game on your Samsung set? Well, you’ll need to do your Super Bowl watching through some kind of NBC-supported streaming app. And not to worry, there are plenty of paths to take.
      For starters, there’s Peacock, NBC’s go-to streaming service. While the basic version of Peacock is actually free, you’ll need to be subscribed to the service’s Premium ($5/month) or Plus plans ($9/month) to be able to watch Super Bowl 2022. Similar to other NBC-hosted sporting events, Super Bowl 2022 streams live through Peacock while being broadcast at the same time on NBC stations.
      Another great gateway to Super Bowl 2022 is through a Hulu + Live TV subscription. The cord-cutter’s dream, Hulu’s Live TV add-on runs $70 per month and will net you a big bounty of paid-cable channels and major network stations, including NBC and your local NBC affiliates. Best of all, before and after the big Bowl, you’ll be able to experience the many other benefits of your Hulu + Live TV subscription. This includes access to Disney+, ESPN+, Hulu’s entire library of movies and shows. Hate ads? For only another $5/month, you can bump that Live TV subscription up to an ad-free package.
      NBC affiliate access is also available through FuboTV, whic is an excellent sports-streaming service, YouTubeTV, both Sling TV packages, and DirecTV Stream.
      How to watch Super Bowl for free on a Samsung Smart TV
      Without getting into the nitty-gritty of mirroring web browsers to your TV (which can have mixed results for live events), the-tried and-true means of getting Super Bowl 2022 for free is through an over-the-air (OTA) antenna.
      Available in a number of shapes, sizes, and applications (primarily indoor/outdoor use), an OTA antenna is manually connected to the coaxial input on the back of your TV. Once plugged in, you’ll run a channel-scan that  will pick up whatever TV stations are being broadcast within a certain mile-cap. Basic indoor antennas can typically grab stations within about a 25-mile range, while more advanced outdoor models can often muster up to about 75 miles or more.
      Source: https://www.digitaltrends.com/home-theater/how-to-watch-super-bowl-2022-on-samsung-smart-tv/
    • By Alex
      Samsung TV Plus offers free tv channels to all Samsung TV owners., over 190! How do you like it? Do you use it? What channels do you like most?
      What is Samsung TV Plus?
      Your Samsung devices come with Samsung TV Plus – Samsung’s free ad-supported Smart TV video service, delivering instant access to news, sports, entertainment, and more. No subscription, additional device, or credit card needed.
      Samsung TV Plus is 100% free. When we say no strings attached, we mean it. No subscriptions, no new fees, no credit card, just free TV.
       

       


    • By Alex
      I have been using Sling TV for the $35 blue bundle here in the US. I tried FuboTV but dropped it because there wasn't enough to make up teh price difference from Sling TV. I have not tried Youtube TV, Hulu Live, or philo. I'm curiuous what you are using for live tv and how you like it as a Samsung TV Tizen app. Not throuh Roku, FireTV or Apple TV.
      How do you like the app mostly, channel surfing, loading ,etc. There's a significant price difference between Sling, Philo, and the others.

    • By Autoguy
      I recently signed up to sling tv streaming and have to say its better on apple tv. On my samsung tv it seems to be slower loading between channels. Apple tv the channels change as if its cable.  If I'm in the guide and click on a channel, I have to then click the "watch" button. I wish they would just remove that park, ON apple tv you click right into the channel for immediate streaming. I think its the way its designed, they should tweak it. Amazon Fire tv is not bad but the samsung Sling TV app needs some updating.
    • By regenitin
      Hello everyone.
      I recently purchased Samsung The Frame 2020 (QA55LS03TAKXXL) in India 2 very important observations from my end.
      I am planning to purchase the Samsung Q600A Soundbar to pair with my TV and wanted to know if my TV supports Q-Symphony. I reached out the support team and they confirmed me that the Q-Symphony function is not a feature of my TV. I wanted to know if Samsung plans to update the operating System to support Q Symphony as this feature is present in Samsung The Frame 2021 which has exact same hardware as Samsung The Frame 2020. Since the support did not have any idea i thought of reaching out to folks on this forum. I am not able to find Amazon Prime Music & Youtube Music apps on the Samsung App Store. These are supposed to be pretty necessary and widely used apps and I am not able to figure out the reason they are not in the store. I would like to know if there are any plans to launch these apps soon. Also let me know if there is any work around to get the apps installed. Thanks in advance for your inputs.
      Best Regards
      Nitin

×
×
  • Create New...