How to use bitcore-lib-cash - 10 common examples

To help you get started, we’ve selected a few bitcore-lib-cash examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github simpleledger / slpjs / examples / 11-get-txns-from-xpub-grpc.ts View on Github external
(async () => {
    for (let i = 0; i < lastFoundActiveAddressIndex + addressGapScanDepth; i++) {
        // get address
        const orderPublickey = hdPublickey.deriveChild(accountDerivation + i.toFixed());
        // @ts-ignore
        const pubkey = new bitcore.PublicKey(orderPublickey.publicKey);
        // @ts-ignore
        const address = bitcore.Address.fromPublicKey(pubkey, bitcore.Networks.mainnet).toString();
        console.log(address);
        //const cashAddr = Utils.toCashAddress(address);
        //console.log(cashAddr);
        const res = await gprc.getAddressTransactions({address});
        if (res.getConfirmedTransactionsList().length > 0) {
            lastFoundActiveAddressIndex = i;
            transactionHistory.push(...res.getConfirmedTransactionsList());
            console.log("Has transactions!");
        }
        console.log(transactionHistory.length);
    }
})();
github monicanagent / cypherpoker.js / src / server / utils / newHDWallet.js View on Github external
pubKey = wallet.neutered().toBase58();//public key in "xpub"
pubKeyHex = wallet.neutered().publicKey.toString("hex"); //public key in hex
privKey = wallet.toBase58(); //private key in "xprv"
privKeyHex = wallet.privateKey.toString("hex"); //private key in hex
wif = wallet.toWIF();
childBIP32_0 = wallet.derivePath("m/0/0");
childBIP32_1 = wallet.derivePath("m/0/1");
if (!testnet) {
   console.log("Wallet root address: "+getAddress(wallet, bitcoreCash.Networks.livenet, true));
   console.log("Wallet \"xpub\": "+pubKey);
   console.log("Wallet \"xprv\": "+privKey);
   console.log("Wallet Import Format (WIF): "+wif);
   console.log("Wallet public key (hex): "+pubKeyHex);
   console.log("Wallet private key (hex): "+privKeyHex);
   console.log("Inital derived address (m/0/0): "+getAddress(childBIP32_0, bitcoreCash.Networks.livenet, true));
   console.log("Inital derived address (m/0/1): "+getAddress(childBIP32_1, bitcoreCash.Networks.livenet, true));
} else {
   console.log("Testnet wallet root address: "+getAddress(wallet, bitcoreCash.Networks.testnet, true));
   console.log("Testnet wallet \"tpub\": "+pubKey);
   console.log("Testnet wallet \"tprv\": "+privKey);
   console.log("Testnet Wallet Import Format (WIF): "+wif);
   console.log("Testnet wallet public key (hex): "+pubKeyHex);
   console.log("Testnet wallet private key (hex): "+privKeyHex);
   console.log("Inital derived address (m/0/0): "+getAddress(childBIP32_0, bitcoreCash.Networks.testnet, true));
   console.log("Inital derived address (m/0/1): "+getAddress(childBIP32_1, bitcoreCash.Networks.testnet, true));
}
console.log ("");

// Some other examples:

//var wallet = newHDWallet(); //create a mainnet top-level HD node (store these details!)
//var wallet = makeHDWallet("xprv9s21ZrQH143K29WDJvBtkuugkRRWAKe3S6soYUVRPnaCK9KXwc8BEJxrncy5mpHyLCFsx39Q6MPnTGT97UxadieivoWFwj1CiqUPdhHDWnY");
github ninjadotorg / handshake-app / src / services / Wallets / BitcoinCash.js View on Github external
createAddressPrivatekey() {
    super.createAddressPrivatekey();
    this.setDefaultNetwork();
    // get Cashaddr
    var address = new bitcore.PrivateKey(this.privateKey).toAddress();
    this.address = address.toString().split(':')[1];
  }
  async getBalance(isFormatNumber) {
github simpleledger / slpjs / examples / 11-get-txns-from-xpub-grpc.ts View on Github external
(async () => {
    for (let i = 0; i < lastFoundActiveAddressIndex + addressGapScanDepth; i++) {
        // get address
        const orderPublickey = hdPublickey.deriveChild(accountDerivation + i.toFixed());
        // @ts-ignore
        const pubkey = new bitcore.PublicKey(orderPublickey.publicKey);
        // @ts-ignore
        const address = bitcore.Address.fromPublicKey(pubkey, bitcore.Networks.mainnet).toString();
        console.log(address);
        //const cashAddr = Utils.toCashAddress(address);
        //console.log(cashAddr);
        const res = await gprc.getAddressTransactions({address});
        if (res.getConfirmedTransactionsList().length > 0) {
            lastFoundActiveAddressIndex = i;
            transactionHistory.push(...res.getConfirmedTransactionsList());
            console.log("Has transactions!");
        }
        console.log(transactionHistory.length);
    }
})();
github simpleledger / slpjs / lib / transactionhelpers.ts View on Github external
}

            // p2pk encode scriptSig

            else if(!(s as ScriptSigP2PKH).pubKeyBuf && (s as ScriptSigP2PKH).signatureBuf) {
                bip62Encoded = this.slp.BITBOX.Script.encode([ (s as ScriptSigP2PKH).signatureBuf ]);
            }

            // throw if input data did not result in encoded scriptSig

            if(!bip62Encoded)
                throw Error("Was not able to set input script for index="+s.index);

            // actually set the input's scriptSig property

            let script = new Bitcore.Script(bip62Encoded);
            txn.inputs[s.index].setScript(script);
         // console.log("scriptSig for index", s.input_index, ":", bip62Encoded.toString('hex'))
        })
github simpleledger / slpjs / examples / 11-get-txns-from-xpub-grpc.ts View on Github external
import * as bitcore from "bitcore-lib-cash";
import { GrpcClient, Transaction } from "grpc-bchrpc-node";
import { Utils } from "../lib/utils";

const gprc = new GrpcClient();

// user variables
const tokenId = "";
const address = "";

const xpub = "xpub661MyMwAqRbcEmunind5AZXnevFW66TB3vq5MHM5Asq8UNaEdTsgk4njwUXW4RGywGK68au91R1rvjQ6SmJQEUwUinjYZPnJA7o72bG5HFr";
// @ts-ignore
const hdPublickey = new bitcore.HDPublicKey(xpub);
const accountDerivation = "m/0/";  //  this is the account part of the non-hardened HD path so, "//<address>/"
let lastFoundActiveAddressIndex = 0;
const addressGapScanDepth = 10;  // this is the gap that will be maintained past the "lastActiveAddressIndex"
let transactionHistory: Transaction[] = [];

// main scanning loop
(async () =&gt; {
    for (let i = 0; i &lt; lastFoundActiveAddressIndex + addressGapScanDepth; i++) {
        // get address
        const orderPublickey = hdPublickey.deriveChild(accountDerivation + i.toFixed());
        // @ts-ignore
        const pubkey = new bitcore.PublicKey(orderPublickey.publicKey);
        // @ts-ignore
        const address = bitcore.Address.fromPublicKey(pubkey, bitcore.Networks.mainnet).toString();
        console.log(address);
        //const cashAddr = Utils.toCashAddress(address);</address>
github bitpay / bitcore / packages / crypto-wallet-core / src / validation / bch / index.ts View on Github external
validateAddress(network: string, address: string): boolean {
      // Check if the input is a valid uri or address
      const URICash = BitcoreCash.URI;
      const AddressCash = BitcoreCash.Address;

       // Bip21 uri
      let uri, uriAddress;
      if (/^bitcoincash:|^bchtest:i/.test(address)) {
        if (URICash.isValid(address)) {
          uri = new URICash(address);
          uriAddress = uri.address.toString();
          return AddressCash.isValid(uriAddress, network);
        }
      }

       // Regular Address: try Bitcoin Cash
      return AddressCash.isValid(address, network);
    }
}
github bitpay / bitcore-mnemonic / lib / messages / index.js View on Github external
function Messages(options) {
  this.builder = Messages.builder(options);

  // map message constructors by name
  for(var key in this.builder.commandsMap) {
    var name = this.builder.commandsMap[key];
    this[name] = this.builder.commands[key];
  }

  if (!options) {
    options = {};
  }
  this.network = options.network || bitcore.Networks.defaultNetwork;
}
github bitpay / bitcore-mnemonic / lib / messages / commands / merkleblock.js View on Github external
'use strict';

var Message = require('../message');
var inherits = require('util').inherits;
var bitcore = require('bitcore-lib-cash');
var BufferUtil = bitcore.util.buffer;
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;

/**
 * Contains information about a MerkleBlock
 * @see https://en.bitcoin.it/wiki/Protocol_documentation
 * @param {MerkleBlock} arg - An instance of MerkleBlock
 * @param {Object=} options
 * @param {Function} options.MerkleBlock - a MerkleBlock constructor
 * @extends Message
 * @constructor
 */
function MerkleblockMessage(arg, options) {
  Message.call(this, options);
  this.MerkleBlock = options.MerkleBlock; // constructor
  this.command = 'merkleblock';
  $.checkArgument(
    _.isUndefined(arg) || arg instanceof this.MerkleBlock,
github simpleledger / slpjs / lib / transactionhelpers.ts View on Github external
// NOTE: Only works for compressed-WIF format

        let ecpair = this.slp.BITBOX.ECPair.fromWIF(wif);

        // we set the previous output for the input
        // again, this is for bitcore-lib input sig generation

        txn.inputs[input_index].output = new Bitcore.Transaction.Output({
            satoshis: input_satoshis, 
            script: redeemScript
        });

        // produce a signature that is specific to this input
        // NOTE: currently only uses ecdsa

        let privateKey = new Bitcore.PrivateKey(wif);
        var sig = Bitcore.Transaction.Sighash.sign(txn, privateKey, sigHashType, input_index, redeemScript, Bitcore.crypto.BN.fromNumber(input_satoshis));
        
        // add have to add the sighash type manually.. :(
        // NOTE: signature is in DER format and is specific to ecdsa &amp; sigHash 0x41

        let sigBuf = Buffer.concat([ sig.toDER(), Buffer.alloc(1, sigHashType) ]);  

        // we can return a object conforming to InputSigData interface

        return {
            index: input_index,
            pubKeyBuf: ecpair.getPublicKeyBuffer(),
            signatureBuf: sigBuf
        }
    }