Bitcoin Development Kit - React Native Module

Last update: Aug 5, 2022

bdk-rn

A React Native version of the Bitcon Development Kit (https://bitcoindevkit.org/)

Table of Contents

Installation

Using npm:

$ npm i git+https://github.com/LtbLightning/bdk-rn.git

Using yarn:

$ yarn add https://github.com/LtbLightning/bdk-rn.git

[IOS Only] Install pods:

npx pod-install
or
cd ios && pod install

Usage

import BdkRn from 'bdk-rn';

// ...

await BdkRn.genSeed({ password: '' });

Library API

All methods work in iOS:

All methods work in Android:

All methods return response as follows:

Promise<Response> = {
  error: true | false; // Method call success return true else return false.
  data: string | object | any; // Different response data based on method call.
}

Following methods can be used with this module. All methods can be called by BdkRn object. Parameters with asterisk(*)** are mandatory.

BdkRn.genSeed({password: ''})

Method Request Parameters
generateMnemonic() {entropy, length}
createExtendedKey() {network, mnemonic, password}
generateXprv() {network, mnemonic, password}
createDescriptor() {type, useMnemonic, mnemonic, password, network, publicKeys, thresold}
createWallet() {mnemonic,password,network,blockChainConfigUrl,blockChainSocket5,retry,timeOut,blockChainName,descriptor,useDescriptor}
getNewAddress() -
getBalance() -
broadcastTx() {address, amount}
getPendingTransactions() {address, amount}
getConfirmedTransactions() {address, amount}

generateMnemomic()

Generate random mnemonic seed phrase. Reference: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#generating-the-mnemonic This will generate a mnemonic sentence from the english word list. The required entropy can be specified as the entropy parameter and can be in multiples of 32 from 128 to 256, 128 is used as default. A word count or length for can be specified instead as the length parameter and can be in multiples of 3 from 12 to 24. 12 is used as default.

When both entropy and length are specified, entropy is used and length is ignored.

// using default values
const response = await BdkRn.generateMnemonic();
// daring erase travel point pull loud peanut apart attack lobster cross surprise

// Specifying entropy of 192 which is the same as specifying length as 18
const response = await BdkRn.generateMnemonic({ entropy: 192 });
// daring erase travel point pull loud peanut apart attack lobster cross surprise actress dolphin gift journey mystery save

createExtendedKey()

This method will create a extendedKeyInfo object using the specified mnemonic seed phrase and password ExtendedKeyInfo creates a key object which encapsulates the mnemonic and adds a private key using the mnemonic and password.

The extended key info object is required to be passed as an argument in some bdk methods.

const key = await BdkRn.createExtendedKey({
  	network: Network.TESTNET
		mnemonic: 'daring erase travel point pull loud peanut apart attack lobster cross surprise',
  	password: ''
	});

// {
// 		fingerprint: 'ZgUK9QXJRYCwnCtYL',
//		mnemonic: 'daring erase travel point pull loud peanut apart attack lobster cross surprise',
//		xpriv: 'tprv8ZgxMBicQKsPd3G66kPkZEuJZgUK9QXJRYCwnCtYLJjEZmw8xFjCxGoyx533AL83XFcSQeuVmVeJbZai5RTBxDp71Abd2FPSyQumRL79BKw'
// }

generateXprv()

generate xprv using mnemonic phrase and password.

const response = await BdkRn.createXprv({ network: Network.TESTNET, mnemonic: '', password: '' });
// tprv8ZgxMBicQKsPd3G66kPkZEuJZgUK9QXJRYCwnCtYLJjEZmw8xFjCxGoyx533AL83XFcSQeuVmVeJbZai5RTBxDp71Abd2FPSyQumRL79BKw

createDescriptor()

Create a variety of descriptors using xprv or mnemonic.

useMnemonic can be true or false. mnemonic_ and *password* are mandatory when useMnemonic is set to true else need to pass value in xprv.

type is a string and can be one of WPKH, P2PKH, p2pkh, pkh, SHP2WPKH, shp2wpkh, p2shp2wpkh, MULTI. WPKH is used as default.

If type is MULTI then need to specufy the signature thresold and publicKeys array. path is optional, 84'/1'/0'/0/* is used by default

const args = {
  type: '',
  useMnemonic: true,
  mnemonic: 'tackle pause sort ten task vast candy skill retire upset lend captain',
  password: '',
  path: '',
  network: '',
  publicKeys: [],
  thresold: 4,
  xprv: '',
};
const response = await BdkRn.createDescriptor(args);
// wpkh(tprv8ZgxMBicQKsPd3G66kPkZEuJZgUK9QXJRYCwnCtYLJjEZmw8xFjCxGoyx533AL83XFcSQeuVmVeJbZai5RTBxDp71Abd2FPSyQumRL79BKw/84'/1'/0'/0/*)

createWallet()

Initialize wallet, returns new address and current balance.

useDescriptor is ethier true or false. Need to pass value in descriptor field if set True else need to pass value in mnemonic.

createWallet with mnemonic

const response = await BdkRn.createWallet({
  mnemonic: 'daring erase travel point pull loud peanut apart attack lobster cross surprise',
  password: '',
  descriptor: '',
  useDescriptor: false,
  network: '',
  blockChainConfigUrl: '',
  blockChainSocket5: '',
  retry: '',
  timeOut: '',
  blockChainName: '',
});

createWallet with descriptor

const response = await BdkRn.createWallet({
  mnemonic: '',
  descriptor:
    'tprv8ZgxMBicQKsPd3G66kPkZEuJZgUK9QXJRYCwnCtYLJjEZmw8xFjCxGoyx533AL83XFcSQeuVmVeJbZai5RTBxDp71Abd2FPSyQumRL79BKw',
  useDescriptor: true,
  password: '',
  network: '',
  blockChainConfigUrl: '',
  blockChainSocket5: '',
  retry: '',
  timeOut: '',
  blockChainName: '',
});

Returned response example:

{
  "data": {
    "address": "tb1qxg8g8cdzgs09cttu3y7lc33udqc4wsesunjnhe",
    "balance": "0" // in sats
  },
  "error": false
}

getNewAddress()

Create new address for wallet.

const response = await BdkRn.getNewAddress();
// tb1qew48u6cfxladqpumcpzl0svdqyvc9h4rqd3dtw

getBalance()

Get balace of wallet.

const response = await BdkRn.getBalance();
{
  "data": "8369", // balance in sats
  "error": false
}

broadcastTx()

Used to send sats to given address.

Required params: address, amount

let address: string = 'tb1qhmk3ftsyctxf2st2fwnprwc0gl708f685t0j3t'; // Wallet address
let amount: number = 2000; // amount in satoshis
const response = await BdkRn.broadcastTx({ address, amount });
{
  "data": "1162badd3d98b97b1c6bb7fc160b7789163c0fcaef99ad841ad8febeb1395864", // transaction id
  "error": false
}

getPendingTransactions()

Get pending transactions

const response = await BdkRn.getPendingTransactions();
[{}];

getConfirmedTransactions()

Get confirmed transactions

const response = await BdkRn.getConfirmedTransactions();
[{}];

Note: Caution this is pre-Alpha at this stage Please consider reviewing, experimenting and contributing ⚡️

Thanks for taking a look!

GitHub

https://github.com/LtbLightning/bdk-rn
Comments
  • 1. Create a wallet with any descriptor

    As far as I understand, bdk-rn currently allows to create a wallet only from a mnemonic. Would it make sense to have createWallet taking a simple descriptor and expose generateExtendedKey and restoreExtendedKey so that the client app has more control?

    Is it what this comment is about? https://github.com/LtbLightning/bdk-rn/blob/edb9ebf64c8012bb89f56bdc17df5f645b17e8d3/android/src/main/java/io/ltbl/bdkrn/BdkFunctions.kt#L104

    Reviewed by testerez at 2022-07-25 15:35
  • 2. Plan for secure storage

    Currently, bdk-rn only store plain data (seedphase, password,..) in localstorage that cause critical security issue. I glad to help you make change via PR, my plan is switch from localstorage to react-native-keychain, but what do you think about it?

    If everything is clear, I will create a PR for it.

    Reviewed by jenkijo at 2022-05-30 04:27
  • 3. Fix `yarn compile`

    yarn compile is currently failing due to typing errors. This prevents installation of the package since compile is called by prepare.

    Here are the errors I was getting:

    > yarn compile
    
    src/index.ts:92:58 - error TS2322: Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.
    
    92         xprv = await (await this.generateXprv({ network, mnemonic, password })).data;
                                                                ~~~~~~~~
    
      src/lib/interfaces.ts:17:3
        17   mnemonic: string;
             ~~~~~~~~
        The expected type comes from property 'mnemonic' which is declared here on type 'CreateExtendedKeyRequest'
    
    src/index.ts:123:30 - error TS2532: Object is possibly 'undefined'.
    
    123         if (thresold == 0 || thresold > publicKeys?.length + 1) throw 'Thresold value in invalid.';
                                     ~~~~~~~~
    
    src/index.ts:123:41 - error TS2532: Object is possibly 'undefined'.
    
    123         if (thresold == 0 || thresold > publicKeys?.length + 1) throw 'Thresold value in invalid.';
                                                ~~~~~~~~~~~~~~~~~~
    
    src/index.ts:153:28 - error TS2532: Object is possibly 'undefined'.
    
    153       if (useDescriptor && descriptor?.split(' ').length > 1) throw 'Descriptor is not valid.';
                                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    src/lib/utils.ts:1:16 - error TS7016: Could not find a declaration file for module 'is_js'. '/Users/tomesterez/projects/bdk-rn/node_modules/is_js/is.js' implicitly has an 'any' type.
      Try `npm i --save-dev @types/is_js` if it exists or add a new declaration (.d.ts) file containing `declare module 'is_js';`
    
    1 import is from 'is_js';
                     ~~~~~~~
    
    
    Found 5 errors.
    
    Reviewed by testerez at 2022-07-28 14:02
  • 4. Modify create wallet interface and descriptor methods

    • change init wallet to createWallet with enhanced interface
    • createWallet can use mnemonic or descriptor
    • added methods generateMnemonic, createExtendedKey and createXprv
    • Multiple types of descriptors can be created with createDescriptor method
    Reviewed by BitcoinZavior at 2022-07-25 23:32
  • 5. Implement getTransactions function

    Description

    This PR add getTransactions function which return all transactions of wallet, include confirmed and unconfirmed transactions

    Example response

    {
       "confirmed":{
          "29b326a7b5fa83c7a910ed4ffe6631f3e35cb812b9b2ba511c20346ba9f596d5":{
             "fees":"18978",
             "height":"2254565",
             "received":"269152",
             "sent":"0",
             "timestamp":"1654657187"
          },
          "3e323b658af359fcd886a422c2b7ea149fcafe1434278005e020cac4f4ac8ad6":{
             "fees":"141",
             "height":"2254398",
             "received":"72000",
             "sent":"0",
             "timestamp":"1654568599"
          },
          "a429080fee431be80056a87cfbc784468c628c4cc9d64f4a207f23776874cf90":{
             "fees":"141",
             "height":"2254563",
             "received":"10000",
             "sent":"0",
             "timestamp":"1654656069"
          }
       },
       "unconfirmed":{
          
       }
    }
    

    Checklists

    Platforms

    • [ ] iOS
    • [x] Android

    New features

    • [x] getTransactions

    Issues

    bdk-swift always return null transaction, I'm not familiar with Swift, but I think the issue is from bdk-swift itself

    Reviewed by jenkijo at 2022-06-09 00:58
  • 6. Transaction creation, signing and broadcast should be separate methods

    Transaction creation, signing and broadcast should be separate methods. This will allow more flexibility in user journeys as well as better error handling. This will also be required when doing multisig transactions.

    Reviewed by BitcoinZavior at 2022-07-30 13:51
  • 7. PoC for using JSI instead of platform binary

    Current implementation uses Android and iOA binaries as core modules for providing bdk functionality.

    Do a Proof of concept to explore use of JSI interface to C++ as a alternate mechanism instead of using platform binaries.

    This has a number of advantages:

    • Eliminates constraints of RN bridge
    • Will allow reuse of bdk ffi rust code directly thus providing more api
    • Will reduce effort and maintenance in using native wrapper code in Android and iOS
    • Performance improvements
    • Eliminate cold start time
    Reviewed by BitcoinZavior at 2022-07-27 11:55
  • 8. Enhance createDescriptor method interface

    Reference: https://github.com/LtbLightning/bdk-rn/tree/modify-create-wallet-interface#createdescriptor

    Use xpriv if provided else use mnemonic, password and network

    Reviewed by BitcoinZavior at 2022-07-27 00:20
  • 9. createWallet: Use`descriptor` if set, otherwise, use `mnemonic`. Throw if none or both are set.

    A simpler API could be to use descriptor if set, otherwise, use mnemonic. Throw if none or both are set.

    Originally posted by @testerez in https://github.com/LtbLightning/bdk-rn/pull/6#discussion_r930035906

    Reviewed by BitcoinZavior at 2022-07-27 00:05
  • 10. Ability to create more types of descriptors

    Large variety of descriptors are possible reference: https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md

    createDescriptor should be able to create as many of these descriptors as possible.

    Reviewed by BitcoinZavior at 2022-07-25 23:40
Related tags
React Native library that implements PayPal Checkout flow using purely native code (swift).
React Native library that implements PayPal Checkout flow using purely native code (swift).

react-native-paypal-swift React Native library that implements PayPal Checkout flow using purely native code (swift). Installation npm install react-n

Jul 24, 2021
A react native interface for integrating payments using Braintree

A react native interface for integrating payments using Braintree

Jul 20, 2022
React Native 实现无侵入自定义下拉刷新组件
React Native 实现无侵入自定义下拉刷新组件

react-native-ly-refresh-control 下拉刷新 iOS 基于MJRefresh 通过RCTCustomRefreshContolProtocol实现RefreshControl组件封装 JS端可以无侵入自定义下拉刷新只需要替换对应的refreshControl Androi

Jul 2, 2022
iOS 15 share play API in react-native

react-native-shareplay iOS 15 share play API in react-native Installation yarn add react-native-shareplay And go to Xcode Capabilities and enable "Gro

Aug 2, 2022
React Native package for interacting with HomeKit devices

React Native package for interacting with HomeKit devices

Dec 24, 2021
react native esptouch

react-native-esptouch One should know that This is a Unofficial project. The official demo is below: EsptouchForAndroid EsptouchForIOS Getting started

Oct 25, 2021
React Native Template for Taro

React Native Template for Taro requirement taro: @tarojs/[email protected]^3.2.0 framework: 'react' quick start install react native library install peerDependenci

Nov 20, 2021
A suite of IoT tools to use with React Native.

react-native-iot-tools WIP. A suite of IoT tools for React Native applications. Package iOS Android @react-native-iot-tools/bluetooth ✅ ❌ @react-nativ

Nov 24, 2021
A testing MQTT react native library

react-native-awesome-testing abc Installation npm install react-native-awesome-testing Usage import { multiply } from "react-native-awesome-testing";

Nov 26, 2021
Encryption/Decryption for React Native

@dhairyasharma/react-native-encryption Encryption/decryption for React Native. Benchmark File Details File Link http://bit.do/benchmarkfile File Size

Mar 6, 2022
Encryption/Decryption for React Native

@dhairyasharma/react-native-encryption Encryption/decryption for React Native. Benchmark File Details File Link http://bit.do/benchmarkfile File Size

Aug 6, 2022
iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android).
iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android).

FinanceReactNative iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android). Data is pulled from Yahoo Finance

Aug 3, 2022
React Native Photo Editor (RNPE)
React Native Photo Editor (RNPE)

React Native Photo Editor (RNPE) ?? Image editor using native modules for iOS an

Aug 3, 2022
Discover Movies and TV shows - React Native
Discover Movies and TV shows -  React Native

movieapp Discover Movies and TV shows Download APK file Download from Google Drive - v2.2.1 What's included Name Description React Native Build Native

Jul 20, 2022
All my React Native examples

ReactNativeExamples All my React Native examples and experiements can be found here. This repo is divided into two sub folders, Instructions git clone

Sep 15, 2021
React Native Twitch application
React Native Twitch application

Notes I'm going to rewrite this project ?? . Be ready to new Twitch application. Twitch This project was built for The Rolling Scopes #18 meetup. As o

Dec 22, 2020
React Native Todo List example app which uses Redux for managing app state
React Native Todo List example app which uses Redux for managing app state

react-native-redux-todo-list A sample todo list app developed by using React Native and Redux. How to run the app Install react-native If you don't ha

Feb 16, 2022
A simple To Do application written in React Native

Example To Do List application in react-native Requirements, install as needed: React Native: $ npm i -g react-native-cli watchman: $ brew install wa

Feb 6, 2022
A property finder application written using React Native

React Native PropertyFinder App This repository accompanies the tutorial I published on Ray Wenderlich's website, which describes the process of build

Jul 20, 2022