Bitcoin Development Kit - React Native Module

Related tags

Miscellaneous bdk-rn
Overview

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!

Comments
  • Create a wallet with any descriptor

    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

    enhancement 
    opened by testerez 4
  • Handle shp2wpkh type correctly in createDescriptor

    Handle shp2wpkh type correctly in createDescriptor

    With the way the switch/case block is written in createDescriptor, the shp2wpkh and p2shp2wpkh cases result in a descriptor without a closing parenthesis e.g. sh(wpkh(...). This change is a refactoring of the switch case block to enable constructing descriptor for all cases correctly, and also improve maintainability and readability.

    opened by shobitb 3
  • Plan for secure storage

    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.

    opened by jenkijo 2
  • Update Method Return Response

    Update Method Return Response

    This PR:

    • Updates the response pattern to be as follows:
    const result = BdkRn.generatemnemomic();
    if (result.isErr()) {
        console.error(result.error.message); // "error message"
        return;
    }
    const mnemonic = result.value;
    
    • Adds @synonymdev/result dependency to package.json.
    • Removes & Replaces previous Response pattern with @synonymdev/result where needed.
    • Updates README.md.
    • This closes #28
    opened by coreyphillips 1
  • Update Method Return Response

    Update Method Return Response

    Do you have any thoughts/feelings on updating the method return response for increased clarity on returned types?

    At Synonym we use the following: https://www.npmjs.com/package/@synonymdev/result

    Example Usage:

    const randomDataCheck = (data): Result<string> => {
        if (!data) return err('No data available');
        return ok('Data was provided');
    };
    
    const result = randomDataCheck('Some data');
    if (result.isErr()) {
        console.error(result.error.message); // "error message"
        return;
    }
    const dataCheckRes = result.value;
    

    This way we always know what's getting returned and it ensures we're checking each response before proceeding. It also helps keep our responses consistent across projects. I would be happy to create a PR with these changes if you believe it would benefit the bdk-rn library.

    opened by coreyphillips 1
  • update createDescriptor api

    update createDescriptor api

    In createDescriptor:

    Remove useMnemonic argument.
instead modify logic to:
use xpriv if set, otherwise, use mnemonic. Throw error if none or both are set.
 if mnemonic flow is chosen network should be specified but password can be optional
 The rest of the arguments should use default values.

    opened by BitcoinZavior 0
  • Fix `yarn compile`

    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.
    
    opened by testerez 0
  • createWallet: Use`descriptor` if set, otherwise, use `mnemonic`. Throw if none or both are set.

    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

    For createWallet:

    Remove useDescriptor argument. instead modify logic to use descriptor if set, otherwise, use mnemonic. Throw error if none or both are set. if mnemonic flow is chosen network should be specified but password can be optional the rest of the arguments should use default values.

    good first issue 
    opened by BitcoinZavior 0
  • Modify create wallet interface and descriptor methods

    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
    opened by BitcoinZavior 0
  • Implement getTransactions function

    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

    opened by jenkijo 0
  • Create descriptors for standard wallet types(bip44/49/84)

    Create descriptors for standard wallet types(bip44/49/84)

    Currently, CreateDescriptors creates descriptors based on the path and script type specified by the user. This is probably not as useful as having the ability to create a descriptor based on a standard BIP. Because it assumes that the user knows the path and script type for a specific wallet type.

    It will be more useful to have the ability to create descriptors for standard wallet types(bip44/49/84) based on BDK templates already available:

    https://docs.rs/bdk/latest/bdk/descriptor/template/index.html

    Templates currently available:

    Bip44 BIP44 template. Expands to pkh(key/44'/{0,1}'/0'/{0,1}/) Bip44Public BIP44 public template. Expands to pkh(key/{0,1}/) Bip49 BIP49 template. Expands to sh(wpkh(key/49'/{0,1}'/0'/{0,1}/)) Bip49Public BIP49 public template. Expands to sh(wpkh(key/{0,1}/)) Bip84 BIP84 template. Expands to wpkh(key/84'/{0,1}'/0'/{0,1}/) Bip84Public BIP84 public template. Expands to wpkh(key/{0,1}/) P2Pkh P2PKH template. Expands to a descriptor pkh(key) P2Wpkh P2WPKH template. Expands to a descriptor wpkh(key) P2Wpkh_P2Sh P2WPKH-P2SH template. Expands to a descriptor sh(wpkh(key))

    Reference for descriptors: https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md

    opened by BitcoinZavior 1
  • getMnemonic() requires network parameter

    getMnemonic() requires network parameter

    It seems omitting the network parameter on getMnemonic() method results in a blocking error: Parameter specified as non-null is null.

    Is there a reason setting the network is required at this stage?

    opened by crukundo 0
  • createWallet: error on bitcoin as network.

    createWallet: error on bitcoin as network.

    Error on iOS: "Code: Init Wallet Error Message: The operation couldn’t be completed. (bdk_rn.BdkError error 26.)" Error on Android: "Code: Init Wallet Error Message: Descriptor(Key(InvalidNetwork))"

    opened by rsbkme 2
  • Transaction creation, signing and broadcast should be separate methods

    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.

    enhancement 
    opened by BitcoinZavior 0
  • PoC for using JSI instead of platform binary

    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
    enhancement 
    opened by BitcoinZavior 0
Releases(v0.1.0)
  • v0.1.0(Oct 10, 2022)

    [0.1.4]

    First published release

    Functionality Added

    • Generate Mnemonic
    • Create Extended Key
    • Create Xprv
    • Create Descriptor
    • Create Wallet
    • Get New Address
    • Get Wallet Balance
    • Broadcast Transaction
    • Get Pending Transactions
    • Get Confirmed Transactions
    • Get Transactions
    Source code(tar.gz)
    Source code(zip)
Owner
Let there be Lightning
Let there be Lightning
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

Tibb 6 Nov 28, 2022
A react native interface for integrating payments using Braintree

A react native interface for integrating payments using Braintree

eKreative 17 Dec 30, 2022
React Native 实现无侵入自定义下拉刷新组件

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

少言 12 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

Popshop Live 27 Oct 16, 2022
React Native package for interacting with HomeKit devices

React Native package for interacting with HomeKit devices

Ibrahim Berat Kaya 4 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

五毛共和国 Wumaoland 0 Oct 25, 2021
React Native Template for Taro

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

null 1 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

Sara Pope 3 Oct 31, 2022
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";

null 0 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

Dhairya Sharma 5 Sep 13, 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

Dhairya Sharma 5 Sep 13, 2022
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

kf 2k Dec 29, 2022
React Native Photo Editor (RNPE)

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

Suman Kamilya 9 Aug 16, 2022
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

June Domingo 1.8k Dec 28, 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

Joseph Khan 93 Oct 2, 2022
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

Ilja Satchok 90 Nov 24, 2022
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

null 43 Oct 11, 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

Joe Maddalone 177 Sep 24, 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

Colin Eberhardt 276 Aug 14, 2022