How to use bech32 - 10 common examples

To help you get started, we’ve selected a few bech32 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 CounterpartyXCP / indexd-server / lib / express.js View on Github external
function addressToScriptId(address) {
    let script = null

    if (address.startsWith('bc') || address.startsWith('tb')) {
      // Regtest starts with 'bc' too
      let b32res = bech32.decode(address)
      let witnessData = bech32.fromWords(b32res.words.slice(1))
      let witnessOpcodes = [0, 0x14]
      script = Buffer.from(witnessOpcodes.concat(witnessData))
    } else {
      script = bitcoin.address.toOutputScript(address, network)
      console.log('Output Script ID', script.toString('hex'))
    }

    return bitcoin.crypto.sha256(script).toString('hex')
  }
github iotexproject / iotex-antenna / src / crypto / address.ts View on Github external
public string(): string {
    // @ts-ignore
    const grouped = bech32.toWords(this.payload);
    return bech32.encode(AddressV1.prefix(), grouped);
  }
github bitcoinjs / bolt11 / payreq.js View on Github external
function decode (paymentRequest, network) {
  if (typeof paymentRequest !== 'string') throw new Error('Lightning Payment Request must be string')
  if (paymentRequest.slice(0, 2).toLowerCase() !== 'ln') throw new Error('Not a proper lightning payment request')
  let decoded = bech32.decode(paymentRequest, Number.MAX_SAFE_INTEGER)
  paymentRequest = paymentRequest.toLowerCase()
  let prefix = decoded.prefix
  let words = decoded.words

  // signature is always 104 words on the end
  // cutting off at the beginning helps since there's no way to tell
  // ahead of time how many tags there are.
  let sigWords = words.slice(-104)
  // grabbing a copy of the words for later, words will be sliced as we parse.
  let wordsNoSig = words.slice(0, -104)
  words = words.slice(0, -104)

  let sigBuffer = wordsToBuffer(sigWords, true)
  let recoveryFlag = sigBuffer.slice(-1)[0]
  sigBuffer = sigBuffer.slice(0, -1)
github bitcoinjs / bolt11 / payreq.js View on Github external
// If they are not equal throw an error
  if (nodePublicKey && tagNodePublicKey && !tagNodePublicKey.equals(nodePublicKey)) {
    throw new Error('payee node key tag and payeeNodeKey attribute must match')
  }

  // make sure if either exist they are in nodePublicKey
  nodePublicKey = tagNodePublicKey || nodePublicKey

  let publicKey = secp256k1.publicKeyCreate(privateKey)

  // Check if pubkey matches for private key
  if (nodePublicKey && !publicKey.equals(nodePublicKey)) {
    throw new Error('The private key given is not the private key of the node public key given')
  }

  let words = bech32.decode(payReqObj.wordsTemp, Number.MAX_SAFE_INTEGER).words

  // the preimage for the signing data is the buffer of the prefix concatenated
  // with the buffer conversion of the data words excluding the signature
  // (right padded with 0 bits)
  let toSign = Buffer.concat([Buffer.from(payReqObj.prefix, 'utf8'), wordsToBuffer(words)])
  // single SHA256 hash for the signature
  let payReqHash = sha256(toSign)

  // signature is 64 bytes (32 byte r value and 32 byte s value concatenated)
  // PLUS one extra byte appended to the right with the recoveryID in [0,1,2,3]
  // Then convert to 5 bit words with right padding 0 bits.
  let sigObj = secp256k1.sign(payReqHash, privateKey)
  let sigWords = hexToWord(sigObj.signature.toString('hex') + '0' + sigObj.recovery)

  // append signature words to the words, mark as complete, and add the payreq
  payReqObj.payeeNodeKey = publicKey.toString('hex')
github forbole / big_dipper / imports / startup / server / util.js View on Github external
pubkeyToBech32: function(pubkey, prefix) {
        // '1624DE6420' is ed25519 pubkey prefix
        let pubkeyAminoPrefix = Buffer.from('1624DE6420', 'hex')
        let buffer = Buffer.alloc(37)
        pubkeyAminoPrefix.copy(buffer, 0)
        Buffer.from(pubkey.value, 'base64').copy(buffer, pubkeyAminoPrefix.length)
        return bech32.encode(prefix, bech32.toWords(buffer))
    },
    bech32ToPubkey: function(pubkey) {
github altangent / lntools / packages / lntools-invoice / __tests__ / decoder.spec.js View on Github external
it("send $24, on mainnet, with fallback (P2WSH) address bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3", () => {
      let input =
        "lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfp4qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q28j0v3rwgy9pvjnd48ee2pl8xrpxysd5g44td63g6xcjcu003j3qe8878hluqlvl3km8rm92f5stamd3jw763n3hck0ct7p8wwj463cql26ava";
      let result = decoder.decode(input);
      let { words } = bech32.decode(
        "bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3",
      );
      let address = Buffer.from(bech32.fromWords(words.slice(1)));
      expect(result.network).to.equal("bc");
      expect(result.valueSat).to.equal("2000000");
      expect(result.timestamp).to.equal(1496314658);
      expect(result.fields.length).to.equal(3);
      expect(result.hashDesc).to.deep.equal(hashDescription);
      expect(result.paymentHash).to.deep.equal(
        Buffer.from("0001020304050607080900010203040506070809000102030405060708090102", "hex"),
      );
      expect(result.fallbackAddresses[0].version).to.equal(0);
      expect(result.fallbackAddresses[0].address).to.deep.equal(address);
      expect(result.signature.r).to.deep.equal(
        Buffer.from("51e4f6446e410a164a6da9f39507e730c26241b4456ab6ea28d1b12c71ef8ca2", "hex"),
      );
      expect(result.signature.s).to.deep.equal(
        Buffer.from("0c9cfe3dffc07d9f8db671ecaa4d20beedb193bda8ce37c59f85f82773a55d47", "hex"),
      );
github cjdelisle / PacketCrypt / js / btc2pkt.js View on Github external
/**
 * (C) Copyright 2019
 * Caleb James DeLisle
 *
 * SPDX-License-Identifier: (LGPL-2.1-only OR LGPL-3.0-only)
 */
const Bech32 = require('bech32');

const addr = process.argv.pop();
try {
    const b = Bech32.decode(addr);
    if (b.prefix === 'bc') {
        console.log(Bech32.encode('pkt', b.words));
    } else if (b.prefix === 'pkt') {
        console.log(Bech32.encode('bc', b.words));
    } else {
        console.log("I don't understand prefix: [" + b.prefix + "]");
    }
} catch (e) {
    console.log(e);
    console.log("Usage: ptc2pkt ");
    console.log("prints the equivilent pkt address");
}
github altangent / lightnode-invoice / src / decoder.spec.js View on Github external
it('send $24, on mainnet, with fallback (P2WSH) address bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3', () => {
      let input =
        'lnbc20m1pvjluezhp58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqspp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqfp4qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q28j0v3rwgy9pvjnd48ee2pl8xrpxysd5g44td63g6xcjcu003j3qe8878hluqlvl3km8rm92f5stamd3jw763n3hck0ct7p8wwj463cql26ava';
      let result = decoder.decode(input);
      let { words } = bech32.decode(
        'bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3'
      );
      let address = Buffer.from(bech32.fromWords(words.slice(1)));
      expect(result.network).to.equal('bc');
      expect(result.amount).to.equal(0.02);
      expect(result.timestamp).to.equal(1496314658);
      expect(result.fields.length).to.equal(3);
      expect(result.hashDesc).to.deep.equal(hashDescription);
      expect(result.paymentHash).to.deep.equal(
        Buffer.from('0001020304050607080900010203040506070809000102030405060708090102', 'hex')
      );
      expect(result.fallbackAddresses[0].version).to.equal(0);
      expect(result.fallbackAddresses[0].address).to.deep.equal(address);
      expect(result.signature.r).to.deep.equal(
        Buffer.from('51e4f6446e410a164a6da9f39507e730c26241b4456ab6ea28d1b12c71ef8ca2', 'hex')
      );
github irisnet / irisnet-crypto / src / chains / cosmos / stake.js View on Github external
MsgBeginRedelegate.prototype.GetSignBytes = function () {
    let msg = {
        delegator_address: BECH32.encode(Config.cosmos.bech32.accAddr,this.DelegatorAddress),
        validator_src_address: BECH32.encode(Config.cosmos.bech32.valAddr,this.ValidatorSrcAddress),
        validator_dst_address: BECH32.encode(Config.cosmos.bech32.valAddr,this.ValidatorDstAddress),
        amount: this.Amount
    };
    let sortMsg = Utils.sortObjectKeys(msg);
    return Amino.MarshalJSON(this.type, sortMsg)
};
github forbole / big_dipper / imports / ui / ledger / ledger.js View on Github external
function bech32ify(address, prefix) {
    const words = bech32.toWords(address)
    return bech32.encode(prefix, words)
}

bech32

Bech32 encoding / decoding

MIT
Latest version published 4 years ago

Package Health Score

73 / 100
Full package analysis